使用HttpClientdopost编写 客户端、服务器与数据库Demo
来源:互联网 发布:淘宝怎么知道卖家电话 编辑:程序博客网 时间:2024/06/05 02:21
目录
原版代码
修改代码
小结
一、原版代码
客户端:
package com.augtwleve;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.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.JTextField;import javax.swing.JLabel;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.util.ArrayList;import java.util.concurrent.TimeUnit;import java.awt.event.ActionEvent;public class Httpclientpost extends JFrame { private JPanel contentPane; private JTextField textField; private JTextField textField_1; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { Httpclientpost frame = new Httpclientpost(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the frame. */ public Httpclientpost() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 450, 300); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); textField = new JTextField(); textField.setBounds(139, 45, 66, 21); contentPane.add(textField); textField.setColumns(10); textField_1 = new JTextField(); textField_1.setBounds(139, 104, 66, 21); contentPane.add(textField_1); textField_1.setColumns(10); JLabel label = new JLabel("用户名"); label.setBounds(22, 48, 54, 15); contentPane.add(label); JLabel label_1 = new JLabel("密码"); label_1.setBounds(22, 107, 54, 15); contentPane.add(label_1); JButton button = new JButton("登录"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { String urlstring="http://localhost:8080/MyserviceTestyuanchuang/MyserverletTestyuanchuang"; HttpClientBuilder builder=HttpClientBuilder.create(); builder.setConnectionTimeToLive(3000, TimeUnit.MILLISECONDS); HttpClient client=builder.build(); HttpPost post=new HttpPost(urlstring); String type="login"; String username=textField.getText(); String password=textField_1.getText(); Jsonobj jsonobj=new Jsonobj(); String jsonstring=jsonobj.json(type, username, password); NameValuePair pair=new BasicNameValuePair("json", jsonstring); ArrayList<NameValuePair> param=new ArrayList<>(); param.add(pair); try { post.setEntity(new UrlEncodedFormEntity(param,"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(); while(line!=null){ System.out.println(line); line=br.readLine(); } } } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); button.setBounds(139, 182, 93, 23); contentPane.add(button); JButton button_1 = new JButton("注册"); button_1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { String urlstring="http://localhost:8080/MyserviceTestyuanchuang/MyserverletTestyuanchuang"; HttpClientBuilder builder=HttpClientBuilder.create(); builder.setConnectionTimeToLive(3000, TimeUnit.MILLISECONDS); HttpClient client=builder.build(); HttpPost post=new HttpPost(urlstring); String type="register"; String username=textField.getText(); String password=textField_1.getText(); Jsonobj jsonobj=new Jsonobj(); String jsonstring=jsonobj.json(type, username, password); NameValuePair pair=new BasicNameValuePair("json", jsonstring); ArrayList<NameValuePair> param=new ArrayList<>(); param.add(pair); try { post.setEntity(new UrlEncodedFormEntity(param,"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(); while(line!=null){ System.out.println(line); line=br.readLine(); } } } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); button_1.setBounds(29, 182, 93, 23); contentPane.add(button_1); JButton button_2 = new JButton("查询"); button_2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String urlstring="http://localhost:8080/MyserviceTestyuanchuang/MyserverletTestyuanchuang"; HttpClientBuilder builder=HttpClientBuilder.create(); builder.setConnectionTimeToLive(3000, TimeUnit.MILLISECONDS); HttpClient client=builder.build(); HttpPost post=new HttpPost(urlstring); String type="query"; String username=""; String password=""; Jsonobj jsonobj=new Jsonobj(); String jsonstring=jsonobj.json(type, username, password); NameValuePair pair=new BasicNameValuePair("json", jsonstring); ArrayList<NameValuePair> param=new ArrayList<>(); param.add(pair); try { post.setEntity(new UrlEncodedFormEntity(param,"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(); while(line!=null){ System.out.println(line); line=br.readLine(); } } } 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(); } } }); button_2.setBounds(284, 182, 93, 23); contentPane.add(button_2); }}
客户端JSON串:
package com.augtwleve;import net.sf.json.JSONObject;public class Jsonobj { private String jsonstring; public Jsonobj(){ } public String json(String type,String username,String password){ JSONObject obj=new JSONObject(); obj.put("Type", type); obj.put("username", username); obj.put("password", password); String jsonstring= obj.toString(); return jsonstring; }}
服务器代码:
package com.augtwleve;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;import net.sf.json.JSONObject;/** * Servlet implementation class MyserverletTestyuanchuang */@WebServlet("/MyserverletTestyuanchuang")public class MyserverletTestyuanchuang extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public MyserverletTestyuanchuang() { 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 username=request.getParameter("username");// String password=request.getParameter("password");// username=Encoding.encoding(username);//编码转换 System.out.println("接收到的数据"+request.getParameter("json")); JSONObject obj=JSONObject.fromObject(request.getParameter("json")); String type=obj.getString("Type"); String username=obj.getString("username"); String password=obj.getString("password"); Mysqlmanager manager=new Mysqlmanager(); String s=manager.judgement(type, username, password); response.setHeader("Content-type","text/html;charset=UTF-8"); System.out.println(s); response.getWriter().append(s); } /** * @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); }}
数据库操作
package com.augtwleve;import java.io.InputStream;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;import java.util.regex.Matcher;import java.util.regex.Pattern;import com.sun.swing.internal.plaf.synth.resources.synth_zh_CN;import net.sf.json.JSONArray;import net.sf.json.JSONObject;/** * 在此方法中判断是哪一种类型: 注册(register) 登录(login) 查询(query) * */public class Mysqlmanager { private Connection connection;//私有化 //get connection方法 public Connection getConnection() { return connection; } //单例设计 private static Mysqlmanager manager; public static synchronized Mysqlmanager newInstance(){ if(manager==null){ manager=new Mysqlmanager(); } return manager; } //在构造器中进行初始化 public Mysqlmanager(){ //注意这是要记得导入mysql的jar包 String driver="com.mysql.jdbc.Driver"; String url="jdbc:mysql://localhost:3306/clazz"; String user="root"; String password="123456"; try { Class.forName(driver); connection=DriverManager.getConnection(url, user, password); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public String judgement(String type,String username,String password){ String s=""; if(type.equals("register")){ s= this.register(username, password); } if(type.equals("login")){ s=this.login(username, password); } if(type.equals("query")){ s=""; s=this.query(username, password); } return s;} public String register(String username,String password){ String s=""; Pattern p = Pattern.compile("^\\w{0,16}$"); Matcher m = p.matcher(username); boolean b = m.matches(); //正则判断 if(b==false){ s="用户名不符合规则请重新命名"; }else{ //重名判断 connection=Mysqlmanager.newInstance().getConnection();//注意导包 String sql="select * from user where user_name=? "; System.out.println("!!!"); PreparedStatement prestate; try { prestate = connection.prepareStatement(sql); prestate.setString(1, username); // prestate.setString(2, password); ResultSet set=prestate.executeQuery(); set.last(); int num=set.getRow(); System.out.println(num); if(num>0){ s="该用户已存在,请重新输入"; }else{ String insert="insert into user(user_name,passerword)values('"+username+"','"+password+"')"; Statement statement=connection.createStatement(); statement.execute(insert); s="注册成功"; } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return s; } public String login(String username,String password){ String s=""; connection=Mysqlmanager.newInstance().getConnection();//注意导包 String sql="select * from user where user_name=? and passerword=?"; PreparedStatement prestate; try { prestate = connection.prepareStatement(sql); prestate.setString(1, username); prestate.setString(2, password); ResultSet set=prestate.executeQuery(); set.last(); int num=set.getRow(); if(num>0){ s="登录成功"; }else{ s="用户名或密码错误,登录失败"; } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return s; } public String query(String username,String password){ String s=""; JSONObject obj = null; String sql="select * from user"; connection=Mysqlmanager.newInstance().getConnection(); try { Statement state=connection.createStatement(); ResultSet set=state.executeQuery(sql); set.first(); //注意jsonarray的用法和使用的位置,如果放在while循环内将会出错 JSONArray json=json=new JSONArray(); while(!set.isAfterLast()){ JSONObject item=new JSONObject(); item.put("username", set.getString("user_name")); item.put("password", set.getString("passerword")); json.add(item); set.next(); } obj=new JSONObject(); obj.put("data", json); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); return "error"; } s="获得的用户名与密码:"+obj.toString(); return s; }}
二、修改后
将客户端中的 注册(register) 登录(login) 查询(query)的方法提出。
客户端:
package com.augtwleve;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.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.JTextField;import javax.swing.JLabel;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.util.ArrayList;import java.util.concurrent.TimeUnit;import java.awt.event.ActionEvent;public class Httpclientpost extends JFrame { private JPanel contentPane; private JTextField textField; private JTextField textField_1; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { Httpclientpost frame = new Httpclientpost(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the frame. */ public Httpclientpost() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 450, 300); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); textField = new JTextField(); textField.setBounds(139, 45, 66, 21); contentPane.add(textField); textField.setColumns(10); textField_1 = new JTextField(); textField_1.setBounds(139, 104, 66, 21); contentPane.add(textField_1); textField_1.setColumns(10); JLabel label = new JLabel("用户名"); label.setBounds(22, 48, 54, 15); contentPane.add(label); JLabel label_1 = new JLabel("密码"); label_1.setBounds(22, 107, 54, 15); contentPane.add(label_1); JButton button = new JButton("登录"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { String username=textField.getText(); String password=textField_1.getText(); ClientMethod.newInstance().login(username, password); } }); button.setBounds(139, 182, 93, 23); contentPane.add(button); JButton button_1 = new JButton("注册"); button_1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { String username=textField.getText(); String password=textField_1.getText(); ClientMethod.newInstance().register(username, password); } }); button_1.setBounds(29, 182, 93, 23); contentPane.add(button_1); JButton button_2 = new JButton("查询"); button_2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String username=textField.getText(); String password=textField_1.getText(); ClientMethod.newInstance().query(username, password); } }); button_2.setBounds(284, 182, 93, 23); contentPane.add(button_2); }}
客户端操作
package com.augtwleve;import java.awt.event.ActionEvent;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.util.ArrayList;import java.util.concurrent.TimeUnit;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;public class ClientMethod { private static ClientMethod method; public static synchronized ClientMethod newInstance(){ if(method==null){ method=new ClientMethod(); } return method; } public ClientMethod(){ } public void login(String username,String password){ String urlstring="http://localhost:8080/MyserviceTestyuanchuang/MyserverletTestyuanchuang"; HttpClientBuilder builder=HttpClientBuilder.create(); builder.setConnectionTimeToLive(3000, TimeUnit.MILLISECONDS); HttpClient client=builder.build(); HttpPost post=new HttpPost(urlstring); JSONObject obj=new JSONObject(); obj.put("Type", "login"); obj.put("username", username); obj.put("password", password); String jsonstring= obj.toString(); NameValuePair pair=new BasicNameValuePair("json", jsonstring); ArrayList<NameValuePair> param=new ArrayList<>(); param.add(pair); try { post.setEntity(new UrlEncodedFormEntity(param,"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(); while(line!=null){ System.out.println(line); line=br.readLine(); } } } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void register(String username,String password){ String urlstring="http://localhost:8080/MyserviceTestyuanchuang/MyserverletTestyuanchuang"; HttpClientBuilder builder=HttpClientBuilder.create(); builder.setConnectionTimeToLive(3000, TimeUnit.MILLISECONDS); HttpClient client=builder.build(); HttpPost post=new HttpPost(urlstring); JSONObject obj=new JSONObject(); obj.put("Type", "register"); obj.put("username", username); obj.put("password", password); String jsonstring= obj.toString(); NameValuePair pair=new BasicNameValuePair("json", jsonstring); ArrayList<NameValuePair> param=new ArrayList<>(); param.add(pair); try { post.setEntity(new UrlEncodedFormEntity(param,"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(); while(line!=null){ System.out.println(line); line=br.readLine(); } } } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void query(String username,String password){ String urlstring="http://localhost:8080/MyserviceTestyuanchuang/MyserverletTestyuanchuang"; HttpClientBuilder builder=HttpClientBuilder.create(); builder.setConnectionTimeToLive(3000, TimeUnit.MILLISECONDS); HttpClient client=builder.build(); HttpPost post=new HttpPost(urlstring); JSONObject obj=new JSONObject(); obj.put("Type", "query"); obj.put("username", username); obj.put("password", password); String jsonstring= obj.toString(); NameValuePair pair=new BasicNameValuePair("json", jsonstring); ArrayList<NameValuePair> param=new ArrayList<>(); param.add(pair); try { post.setEntity(new UrlEncodedFormEntity(param,"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(); while(line!=null){ System.out.println(line); line=br.readLine(); } } } 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(); } }}
服务器
package com.augtwleve;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;import net.sf.json.JSONObject;/** * Servlet implementation class MyserverletTestyuanchuang */@WebServlet("/MyserverletTestyuanchuang")public class MyserverletTestyuanchuang extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public MyserverletTestyuanchuang() { 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 username=request.getParameter("username");// String password=request.getParameter("password");// username=Encoding.encoding(username);//编码转换 String s=""; System.out.println("接收到的数据"+request.getParameter("json")); JSONObject obj=JSONObject.fromObject(request.getParameter("json")); String type=obj.getString("Type"); String username=obj.getString("username"); String password=obj.getString("password"); if(type.equals("register")){ s=Mysqlmanager.newInstance().register(username, password); } if(type.equals("login")){ s=Mysqlmanager.newInstance().login(username, password); } if(type.equals("query")){ s=Mysqlmanager.newInstance().query(username, password); }// Mysqlmanager manager=new Mysqlmanager();// String s=manager.judgement(type, username, password); response.setHeader("Content-type","text/html;charset=UTF-8"); System.out.println(s); response.getWriter().append(s); } /** * @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); }}
服务器操作
package com.augtwleve;import java.io.InputStream;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;import java.util.regex.Matcher;import java.util.regex.Pattern;import com.sun.swing.internal.plaf.synth.resources.synth_zh_CN;import net.sf.json.JSONArray;import net.sf.json.JSONObject;/** * 在此方法中判断是哪一种类型: 注册(register) 登录(login) 查询(query) * */public class Mysqlmanager { private Connection connection;//私有化 //get connection方法 public Connection getConnection() { return connection; } //单例设计 private static Mysqlmanager manager; public static synchronized Mysqlmanager newInstance(){ if(manager==null){ manager=new Mysqlmanager(); } return manager; } //在构造器中进行初始化 public Mysqlmanager(){ //注意这是要记得导入mysql的jar包 String driver="com.mysql.jdbc.Driver"; String url="jdbc:mysql://localhost:3306/clazz"; String user="root"; String password="123456"; try { Class.forName(driver); connection=DriverManager.getConnection(url, user, password); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public String judgement(String type,String username,String password){ String s=""; if(type.equals("register")){ s= this.register(username, password); } if(type.equals("login")){ s=this.login(username, password); } if(type.equals("query")){ s=""; s=this.query(username, password); } return s;} public String register(String username,String password){ String s=""; Pattern p = Pattern.compile("^\\w{0,16}$"); Matcher m = p.matcher(username); boolean b = m.matches(); //正则判断 if(b==false){ s="用户名不符合规则请重新命名"; }else{ //重名判断 connection=Mysqlmanager.newInstance().getConnection();//注意导包 String sql="select * from user where user_name=? "; System.out.println("!!!"); PreparedStatement prestate; try { prestate = connection.prepareStatement(sql); prestate.setString(1, username); // prestate.setString(2, password); ResultSet set=prestate.executeQuery(); set.last(); int num=set.getRow(); System.out.println(num); if(num>0){ s="该用户已存在,请重新输入"; }else{ String insert="insert into user(user_name,passerword)values('"+username+"','"+password+"')"; Statement statement=connection.createStatement(); statement.execute(insert); s="注册成功"; } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return s; } public String login(String username,String password){ String s=""; connection=Mysqlmanager.newInstance().getConnection();//注意导包 String sql="select * from user where user_name=? and passerword=?"; PreparedStatement prestate; try { prestate = connection.prepareStatement(sql); prestate.setString(1, username); prestate.setString(2, password); ResultSet set=prestate.executeQuery(); set.last(); int num=set.getRow(); if(num>0){ s="登录成功"; }else{ s="用户名或密码错误,登录失败"; } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return s; } public String query(String username,String password){ String s=""; JSONObject obj = null; String sql="select * from user"; connection=Mysqlmanager.newInstance().getConnection(); try { Statement state=connection.createStatement(); ResultSet set=state.executeQuery(sql); set.first(); System.out.println("1111111"); JSONArray json=json=new JSONArray();; while(!set.isAfterLast()){ JSONObject item=new JSONObject(); item.put("username", set.getString("user_name")); item.put("password", set.getString("passerword")); json.add(item); set.next(); } obj=new JSONObject(); obj.put("data", json); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); return "error"; } s="获得的用户名与密码:"+obj.toString(); return s; }}
小结
1、注意JsonArray的使用方法
2、注意导包,有些jar包必须在lib底下
3、注意将方法单抽出来
4、学会HttpClientdopost的使用
5、编写思路
6
0 0
- 使用HttpClientdopost编写 客户端、服务器与数据库Demo
- Android TCP 文件客户端与服务器DEMO
- Android TCP 文件客户端与服务器DEMO
- Android TCP 文件客户端与服务器DEMO
- Android TCP 文件客户端与服务器DEMO
- UDP协议服务器、客户端使用实例Demo
- Delphi编写soap服务器与客户端程序
- Delphi编写soap服务器与客户端程序
- Delphi编写soap服务器与客户端程序
- (1) 编写服务器与客户端
- 客户端服务器通信demo
- scrapy爬虫++mysql数据库+tomcat服务器+android客户端项目demo
- python socket之tcp服务器与客户端demo
- Socket+NIO实现客户端与服务器的通信的Demo
- 编写服务器和客户端
- ORACLE客户端与数据库服务器连接
- 使用CXF编写简单客户端与服务端
- Thrift安装与服务器、客户端的编写运行演示
- 备忘----创建套接字进行地址和端口进行网络序转换时使用ipv4和ipv6都通用的函数
- Robot Framework 快速入门
- 【树链剖分】【NOI 2015】【bzoj 4196】软件包管理器
- iOS小白进阶之旅(一)
- jq和css3图片拉近效果
- 使用HttpClientdopost编写 客户端、服务器与数据库Demo
- HDOJ Page Rank 5097【2014上海邀请赛H题-简单矩阵】
- 计算机系统(三)CPU读并解释存储在存储器中的指令
- Dom4j解析xml文件-操作节点和属性及写入其他xml文件
- tomcat同时部署两个项目的问题
- MySQL 存储引擎 MyISAM 与 InnoDB 的对比
- Android API Guides学习4——Fragments
- Linux 内核下发送 SYN 段
- LINUX图文教程