第五周第四天(doPOST实例【注册、登录、检索】)
2015-08-13 20:29
627 查看
[code]package com.day4_2015_08_13; import java.io.IOException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; 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 MyServer */ @WebServlet("/MyServer") public class MyServer extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public MyServer() { super(); } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse * response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String json = request.getParameter("json"); String s = ""; System.out.println("得到的数据" + json); JSONObject obj = JSONObject.fromObject(json); String type = obj.getString("type"); if (type.equals("register")) { JSONObject data = obj.getJSONObject("data"); String userName = data.getString("userName"); String password = data.getString("password"); s = SQLOperate.newInstance().register(userName, password); } else if (type.equals("Login")) { JSONObject data = obj.getJSONObject("data"); String userName = data.getString("userName"); String password = data.getString("password"); s = SQLOperate.newInstance().login(userName, password); } else if (type.equals("Select")) { s = SQLOperate.newInstance().select(); } response.setHeader("Content-type", "text/html;charset=UTF-8"); // 让浏览器以UTF-8编码格式解析 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.day4_2015_08_13; /** * 放各种网络联接的方法 * 单例设计模式 */ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; 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 MyHttpMethod { private MyHttpMethod (){ } private static MyHttpMethod manager; public static synchronized MyHttpMethod newInstance(){ if(manager==null){ manager=new MyHttpMethod(); } return manager; } /** * 注册 * @param username * @param password * @return */ public String register(String userName,String password){ String url="http://localhost:8080/MyServer1/MyServer"; 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", "register");//{type:"register"} JSONObject data=new JSONObject();//{} data.put("userName", userName);//{username:"zhangsan"} data.put("password", password);//{username:"zhangsan",password:"123456"} obj.put("data", data);//{type:"register",data:{username:"zhangsan",password:"123456"}} NameValuePair pair1=new BasicNameValuePair("json", obj.toString()); ArrayList<NameValuePair> params=new ArrayList<>(); params.add(pair1); try { post.setEntity(new UrlEncodedFormEntity(params, "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==200){ HttpEntity entity=response.getEntity(); InputStream is=entity.getContent(); BufferedReader br=new BufferedReader(new InputStreamReader(is)); String line=br.readLine(); //带有缓冲区的字符串是可变的append方法是字符连接 StringBuffer buffer=new StringBuffer(); while(line!=null){ buffer.append(line); System.out.println(line); line=br.readLine(); } return buffer.toString(); } } 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(); } return null; } /** * 登录 * @param username * @param password * @return */ public String login(String userName,String password){ String url="http://localhost:8080/MyServer1/MyServer"; 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", "Login");//{type:"register"} JSONObject data=new JSONObject();//{} data.put("userName", userName);//{username:"zhangsan"} data.put("password", password);//{username:"zhangsan",password:"123456"} obj.put("data", data);//{type:"register",data:{username:"zhangsan",password:"123456"}} NameValuePair pair1=new BasicNameValuePair("json", obj.toString()); ArrayList<NameValuePair> params=new ArrayList<>(); params.add(pair1); try { post.setEntity(new UrlEncodedFormEntity(params, "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==200){ HttpEntity entity=response.getEntity(); InputStream is=entity.getContent(); BufferedReader br=new BufferedReader(new InputStreamReader(is)); String line=br.readLine(); //带有缓冲区的字符串是可变的 //append方法是字符连接 StringBuffer buffer=new StringBuffer(); while(line!=null){ buffer.append(line); System.out.println(line); line=br.readLine(); } return buffer.toString(); } } 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(); } return null; } /** * 查找 * @return */ public String select(){ String url="http://localhost:8080/MyServer1/MyServer"; 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", "Select");//{type:"register"} NameValuePair pair1=new BasicNameValuePair("json", obj.toString()); ArrayList<NameValuePair> params=new ArrayList<>(); params.add(pair1); try { post.setEntity(new UrlEncodedFormEntity(params, "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==200){ HttpEntity entity=response.getEntity(); InputStream is=entity.getContent(); BufferedReader br=new BufferedReader(new InputStreamReader(is)); String line=br.readLine(); //带有缓冲区的字符串是可变的append方法是字符连接 StringBuffer buffer=new StringBuffer(); while(line!=null){ buffer.append(line); System.out.println(line); line=br.readLine(); } return buffer.toString(); } } 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(); } return null; } } ************************************************** package com.day4_2015_08_13; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import net.sf.json.JSONArray; import net.sf.json.JSONObject; //单例 public class SQLOperate { private SQLOperate(){ } private static SQLOperate op; public static synchronized SQLOperate newInstance(){ if(op==null){ op=new SQLOperate(); } return op; } public String register(String userName,String password){ JSONObject obj=new JSONObject(); Connection conn=SQLManager.newInstance().getConn(); try { PreparedStatement state=conn.prepareStatement("insert into user (userName,password)values(?,?)"); state.setString(1, userName); state.setString(2, password); state.execute(); obj.put("code", 0); obj.put("message", "成功注册"); } catch (SQLException e) { obj.put("code", 1); obj.put("message", "注册失败"); e.printStackTrace(); } return obj.toString(); } public String login(String userName,String password){ JSONObject obj=new JSONObject(); Connection conn=SQLManager.newInstance().getConn(); try { PreparedStatement state=conn.prepareStatement("select * from user where userName=?"); state.setString(1, userName); ResultSet set=state.executeQuery(); set.last(); int num=set.getRow(); if(num==0){ obj.put("code", 1); obj.put("message", "用户名错误"); return obj.toString(); } PreparedStatement state2=conn.prepareStatement("select * from user where userName=? and password=?"); state2.setString(1, userName); state2.setString(2, password); ResultSet set2=state2.executeQuery(); set2.last(); int num2=set2.getRow(); if(num2>0){ obj.put("code", 0); obj.put("message", "登录成功"); return obj.toString(); } } catch (SQLException e) { obj.put("code", 1); obj.put("message", "登录失败"); e.printStackTrace(); } return obj.toString(); } public String select(){ JSONObject obj=new JSONObject(); Connection conn=SQLManager.newInstance().getConn(); try { PreparedStatement state=conn.prepareStatement("select * from user"); ResultSet set=state.executeQuery(); set.first(); JSONArray array=new JSONArray(); while(!set.isAfterLast()){ JSONObject item=new JSONObject(); item.put("password",set.getString("password")); item.put("userName", set.getString("userName")); array.add(item); set.next(); } obj.put("code", 0); obj.put("message", "查询成功"); obj.put("data", array); } catch (SQLException e) { obj.put("code", 1); obj.put("message", "查询失败"); e.printStackTrace(); } return obj.toString(); } } **************************************************** package com.day4_2015_08_13; import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import javax.swing.JTextField; import javax.swing.JLabel; import java.awt.Color; import javax.swing.JButton; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; public class MyHttp extends JFrame { private JPanel contentPane; private JTextField textFieldYonghuming; private JTextField textFieldMima; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { MyHttp frame = new MyHttp(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the frame. */ public MyHttp() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 450, 300); contentPane = new JPanel(); contentPane.setBackground(Color.PINK); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); JLabel label = new JLabel("用户名"); label.setBounds(65, 59, 54, 15); contentPane.add(label); JLabel label_1 = new JLabel("密码"); label_1.setBounds(65, 142, 54, 15); contentPane.add(label_1); JButton button = new JButton("注册"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String message=MyHttpMethod.newInstance().register(textFieldYonghuming.getText(), textFieldMima.getText()); System.out.println(message); } }); button.setBounds(73, 201, 79, 23); contentPane.add(button); textFieldYonghuming = new JTextField(); textFieldYonghuming.setBounds(152, 48, 133, 29); contentPane.add(textFieldYonghuming); textFieldYonghuming.setColumns(10); textFieldMima = new JTextField(); textFieldMima.setBounds(152, 131, 133, 29); contentPane.add(textFieldMima); textFieldMima.setColumns(10); JButton btnNewButton = new JButton("登录"); btnNewButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { System.out.println("开始登录"); String message=MyHttpMethod.newInstance().login(textFieldYonghuming.getText(), textFieldMima.getText()); System.out.println(message); System.out.println("登录完成"); } }); btnNewButton.setBounds(183, 201, 79, 23); contentPane.add(btnNewButton); JButton btnNewButton_1 = new JButton("查询"); btnNewButton_1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String message=MyHttpMethod.newInstance().select(); System.out.println(message); } }); btnNewButton_1.setBounds(287, 201, 79, 23); contentPane.add(btnNewButton_1); } }
相关文章推荐
- 运维大局观
- openstack-juno安装记录
- 定制Dockerfile实现redis cluster的docker化部署及集群管理
- [转]tornado ioloop start 的过程
- docker强制批量删除none的image镜像
- linux系统下载:Ubuntu 14.10 ISO 正式版镜像文件
- 使用iptables管理docker容器做端口映射网络
- Ubuntu安装OpenSSL
- 《学习opencv》笔记——矩阵和图像处理——cvAnd、cvAndS、cvAvg and cvAvgSdv
- 解决docker不能绑定静态的外网固定ip的问题
- 云中双边滤波器——基于opencv图像结构
- Xamarin.Forms之OnElementPropertyChanged那些事
- 两台Linux主机通信(服务器客户端搭建)
- SELinux深入理解
- Linux2.6.38内核启动流程分析
- 查看当前ubuntu版本号
- linux下tar的用法
- Linux内核同步方法
- 用@property声明的NSString(或NSArray,NSDictionary)经常使用copy关键字,为什么?如果改用strong关键字,可能造成什么问题?
- 编译通过的U-boot和使用的arm-linux-gcc编译器