(8.13)客户端、服务器交互用json,同时去数据库检查,将0、1设置为静态常量(便于加注释它是干什么的,另外多建类,单例模式的使用)
2015-08-13 11:34
633 查看
服务器端程序
另外JSONArray的使用,可以用add向其中添加JSONObject对象,除此之外连接网络可能是一个耗时的事情,最好另起一个线程。在java Resouce的src下的服务器主程序,同时需要把包都导入到WEB-INF下的lib下,需要导入json的包和数据库驱动的包
//在java Resouce的src下的服务器主程序 import java.io.IOException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class webproject */ @WebServlet("/webproject") public class webproject extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public webproject() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub //String str=request.getParameter("username"); //String pass=request.getParameter("password"); String json=request.getParameter("json"); //str=Encoding.doEncoding(str); //System.out.println(str+""); // try { // Thread.sleep(10000); // } catch (InterruptedException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // Connection conn=MySql.newInstance().getConnect(); // try { // PreparedStatement state=conn.prepareStatement("select * from user where user_name=? and user_word=?"); // state.setString(1, str); // state.setString(2, pass); // ResultSet set =state.executeQuery(); // set.last(); // int num=set.getRow(); // if(num==1){ // System.out.println("登录成功"); // }else{ // System.out.println("不存在用户名或密码"); // } // } catch (SQLException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } //new Check(str, pass); Check2 check=new Check2(json); String retu=check.getToReturn(); response.setHeader("Content-type","text/html;charset=UTF-8"); response.getWriter().append(retu); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } } "*****************检查数据库,以及区分登录和注册********************" import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import net.sf.json.JSONObject; public class Check2 { /** * 导入的包都放在WEB-INF下的lib中 * 对传递过来的数据进行检查,判断是登录还是注册 * @param json */ private Connection conn; private String toReturn; public Check2(String json) { conn = MySql.newInstance().getConnect(); JSONObject obj = JSONObject.fromObject(json); String type = obj.getString("type"); if (type.equals("register")) { register(obj); }else if(type.equals("login")){ login(obj); } } /** * * @return 得到返回的json数据,返回调用的地方 */ public String getToReturn() { return toReturn; } /** * * @param obj 传入要解析的json数据 * 然后调用数据库,对数据库的内容进行检查,如不存在用户则进行注册 * 否则返回注册失败的信息 */ public void register(JSONObject obj){ JSONObject data = JSONObject.fromObject(obj.getString("data")); String username = data.getString("username"); String password = data.getString("password"); String register = "insert into user (user_name,user_word)values(?,?)"; try { String name = "select * from user where user_name=?"; PreparedStatement state1 = conn.prepareStatement(name); state1.setString(1, username); ResultSet set = state1.executeQuery(); set.last(); // and user_word=? int num = set.getRow(); JSONObject objectClient = new JSONObject(); JSONObject toClientdata = new JSONObject(); if (num == 1) { System.out.println("用户名已存在"); objectClient.put("code", "0"); toClientdata.put("message", "注册失败"); objectClient.put("toClientdata", toClientdata); toReturn=objectClient.toString(); } else { PreparedStatement state = conn.prepareStatement(register); state.setString(1, username); // 对占位符设置值,占位符顺序从1开始,第一个参数是占位符的位置,第二个参数是占位符的值。 state.setString(2, password); state.executeUpdate(); System.out.println("成功注册"); objectClient.put("code", "1"); toClientdata.put("message", "成功注册"); objectClient.put("toClientdata", toClientdata); toReturn=objectClient.toString(); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * * @param obj 传入要解析的json数据 * 解析后,连接数据库,然后进行判断,若存在,则返回用户登录成功 */ public void login(JSONObject obj) { JSONObject data = JSONObject.fromObject(obj.getString("data")); String username = data.getString("username"); JSONObject objectClient = new JSONObject(); JSONObject toClientdata = new JSONObject(); String password = data.getString("password"); String login = "select * from user where user_name=? and user_word=?"; try { String name = "select * from user where user_name=?"; PreparedStatement state = conn.prepareStatement(name); state.setString(1, username); ResultSet set = state.executeQuery(); set.last(); // and user_word=? int num = set.getRow(); if (num == 1) { PreparedStatement state1 = conn.prepareStatement(login); state1.setString(1, username); state1.setString(2, password); ResultSet set1 = state1.executeQuery(); set1.last(); // and user_word=? int num1 = set1.getRow(); if (num1 == 1) { System.out.println("用户登录成功"); objectClient.put("code", "1"); toClientdata.put("message", "登录成功"); objectClient.put("toClientdata", toClientdata); toReturn = objectClient.toString(); } else { System.out.println("用户登录失败"); objectClient.put("code", "0"); toClientdata.put("message", "密码错误,登录失败"); objectClient.put("toClientdata", toClientdata); toReturn = objectClient.toString(); } } else { System.out.println("不存在用户名"); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } "******************连接数据库的单例模式类********************" import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; /** * 使用单例模式 * 创建于数据库的连接 * 这些语句都是写在服务器程序中,将mysql-jdbc.jar拷贝到服务器WEB-INF的lib目录下 * @author Administrator * */ public class MySql { private Connection connect; private static MySql manger; public static synchronized MySql newInstance() { if (manger == null) { manger = new MySql(); } return manger; } public Connection getConnect() { return connect; } public MySql() { String driver = "com.mysql.jdbc.Driver"; String name = "root"; String pass = "123456"; String uri = "jdbc:mysql://localhost:3306/clazz"; try { Class.forName(driver); connect = DriverManager.getConnection(uri, name, pass); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
客户端程序(新建一个java工程)
长度可变的字符串
**//带有缓冲区的字符串是可变的append方法是字符连接,StringBuffer buffer=new StringBuffer();
buffer.append(line);**
因为用的HttpClient 所以需要导入HttpClient的jar包,json的包
import java.awt.BorderLayout; import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import org.apache.http.HttpConnection; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.message.BasicNameValuePair; import net.sf.json.JSONObject; import javax.swing.JButton; import java.awt.event.ActionListener; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.sql.Connection; import java.util.ArrayList; import java.util.concurrent.TimeUnit; import java.awt.event.ActionEvent; import javax.swing.JTextField; import javax.swing.JLabel; public class HttpDoPost extends JFrame { private JPanel contentPane; private JTextField textFieldName; private JTextField textFieldPassWord; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { HttpDoPost frame = new HttpDoPost(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the frame. */ public HttpDoPost() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 528, 343); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); JButton btnNewButton = new JButton("HttpClientDoPost"); btnNewButton.setBounds(392, 71, 110, 50); btnNewButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String register="register"; //调用登录的方法 distinguish(register); } }); contentPane.setLayout(null); contentPane.add(btnNewButton); JButton btnNewButton_1 = new JButton("用户登录"); btnNewButton_1.setBounds(409, 189, 93, 41); btnNewButton_1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { String log="login"; distinguish(log); } }); contentPane.add(btnNewButton_1); textFieldName = new JTextField(); textFieldName.setBounds(146, 76, 110, 31); contentPane.add(textFieldName); textFieldName.setColumns(10); textFieldPassWord = new JTextField(); textFieldPassWord.setBounds(146, 199, 110, 31); contentPane.add(textFieldPassWord); textFieldPassWord.setColumns(10); JLabel lblNewLabel = new JLabel("用户名:"); lblNewLabel.setBounds(41, 80, 76, 32); contentPane.add(lblNewLabel); JLabel lblNewLabel_1 = new JLabel("密码:"); lblNewLabel_1.setBounds(41, 202, 76, 28); contentPane.add(lblNewLabel_1); } /** * * @param sum 传入从服务器返回要分析的字符串 * 得到返回的message * */ public void analy(String sum) { JSONObject objclient = JSONObject.fromObject(sum); String returncode = objclient.getString("code"); if (returncode.equals("1")) { JSONObject data = JSONObject.fromObject(objclient.getString("toClientdata")); String messg = data.getString("message"); System.out.println(messg); } else { JSONObject data = JSONObject.fromObject(objclient.getString("toClientdata")); String messg = data.getString("message"); System.out.println(messg); } } /** * * @param dis 判断type,因为服务器端通过type判断,所以通过传入值,来改变type类型 * 然后发送给服务器,最后调用analy对返回数据进行解析,得到想要的值 */ public void distinguish(String dis){ String url = "http://192.168.0.31:8080/MySeverTest/webproject"; HttpClientBuilder builder = HttpClientBuilder.create(); builder.setConnectionTimeToLive(3000, TimeUnit.MILLISECONDS); HttpClient client = builder.build(); HttpPost post = new HttpPost(url); JSONObject obj = new JSONObject(); obj.put("type", dis); JSONObject data = new JSONObject(); data.put("username", textFieldName.getText()); data.put("password", textFieldPassWord.getText()); obj.put("data", data); // 检查发出的内容 // System.out.println(obj.toString()); NameValuePair pair = new BasicNameValuePair("json", obj.toString()); // NameValuePair pair1=new BasicNameValuePair("password", // "123456"); ArrayList<NameValuePair> list = new ArrayList<>(); list.add(pair); try { post.setEntity(new UrlEncodedFormEntity(list, "UTF-8")); post.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); HttpResponse response = client.execute(post); int code = response.getStatusLine().getStatusCode(); if (code == HttpURLConnection.HTTP_OK) { HttpEntity entity = response.getEntity(); InputStream is = entity.getContent(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String line = br.readLine(); String sum = ""; if (line != null) { // System.out.println(line); sum += line; line = br.readLine(); } analy(sum); } } catch (UnsupportedEncodingException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (ClientProtocolException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } }
相关文章推荐
- redis getone getcount getlist update
- explain mysql性能优化
- 浅谈SQL语句优化经验
- mongoDB搭建和运行简单的增删改查操作
- 获取当天某个产品中用户的交易数量redis 零点过期数据
- MYSQL 常用 SQL 整理
- Mysql函数(全)
- SQL之EXPLAIN语法
- PL/SQL Developer记住用户名和密码
- MySQL常见问题汇总(修改密码/远程权限)
- mysql多字段唯一索引
- MySQL逗号分割字段的行列转换技巧
- 数据库备份存储过程
- SQL中Group By的使用
- oracle10g启动报错ora-00214
- redis基础用法
- Redis深入浅出----演讲
- mysql管理
- innodb中master线程的调度的算法改进(mysql 5.6.26)
- 天云星数据库介绍