JAVA基础一大堆0813Web项目

来源:互联网 发布:淘宝上的台式机能买吗 编辑:程序博客网 时间:2024/04/30 05:30

  说起来太麻烦了,直接上图。
  这里写图片描述
  这里写图片描述

服务器代码

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 MyTestServlet */@WebServlet("/MyTestServlet")public class MyTestServlet extends HttpServlet {    private static final long serialVersionUID = 1L;    /**     * @see HttpServlet#HttpServlet()     */    public MyTestServlet() {        super();    }    /**     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse     *      response)     */    protected void doGet(HttpServletRequest request, HttpServletResponse response)            throws ServletException, IOException {        String json = request.getParameter("json");        if (json != null) {            System.out.println(json);            JSONObject obj=JSONObject.fromObject(json);//jar包要放在WebContent/WEB-INF/lib包里!            String type = obj.getString("type");            String back="";            if (type.equals(Config.REGISTER)) {                JSONObject data = obj.getJSONObject("data");                String userName = data.getString("username");                String password = data.getString("password");                System.out.println(userName + password);                back=SQLOperate.newInstance().register(userName, password);                // 让浏览器以UTF-8编码格式解析                response.setHeader("Content-type", "text/html;charset=UTF-8");                response.getWriter().append(back);// 输出,返回给客户端            }else if(type.equals(Config.SIGN_IN)){                JSONObject data = obj.getJSONObject("data");                String userName = data.getString("username");                String password = data.getString("password");                System.out.println(userName + password);                back=SQLOperate.newInstance().signIn(userName, password);            }else if(type.equals(Config.SELECT_ALL)){                back=SQLOperate.newInstance().selectAll();            }            response.setHeader("Content-type", "text/html;charset=UTF-8");            response.getWriter().append(back);// 输出,返回给客户端        }    }    /**     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse     *      response)     */    protected void doPost(HttpServletRequest request, HttpServletResponse response)            throws ServletException, IOException {        doGet(request, response);    }}//configpublic class Config {    public static final String REGISTER="register";    public static final String SELECT_ALL="selectall";    public static final String SIGN_IN="signin";}//封装的方法import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import org.eclipse.jdt.internal.compiler.lookup.PackageBinding;import net.sf.json.JSONArray;import net.sf.json.JSONObject;public class SQLOperate {    public static final int SUCCESS = 0;    public static final int FAIL = 1;    public static final int ERROR = 2;    private SQLOperate() {    }    private static SQLOperate operate;    public static synchronized SQLOperate newInstance() {        if (operate == null) {            operate = new SQLOperate();        }        return operate;    }    /**     * 实现客户端在服务器的注册     *      * @param userName     *            传入客户端输入的用户名     * @param password     *            传入客户端输入的密码     * @return 返回发送给客户端的字符串     */    public String register(String userName, String password) {        JSONObject obj = new JSONObject();        String back = "";        Connection conn = SQLManager.newInstance().getConnection();        try {            PreparedStatement state1 = conn.prepareStatement("select * from user where name=?");            state1.setString(1, userName);            ResultSet set = state1.executeQuery();            set.last();            int num = set.getRow();            System.out.println(num);            if (num == 1) {                obj.put("code", ERROR);                obj.put("result", "该账号已注册");            } else {                //必须加else,不加的话就算是已经注册的账户,下面的程序继续执行重复添加                PreparedStatement state = conn.prepareStatement("insert into user(name,password)values(?,?)");                state.setString(1, userName);                state.setString(2, password);                state.execute();                obj.put("code", SUCCESS);                obj.put("result", "注册成功");            }        } catch (SQLException e1) {            obj.put("code", FAIL);            obj.put("result", "注册失败");            e1.printStackTrace();        }        return obj.toString();    }    /**     * 登录服务器     *      * @param userName     *            传入客户端的用户名     * @param password     *            传入客户端的密码     * @return 返回服务器传出的数据     */    public String signIn(String userName, String password) {        JSONObject obj = new JSONObject();        Connection conn = SQLManager.newInstance().getConnection();        try {            PreparedStatement state = conn.prepareStatement("select * from user where name=?");            state.setString(1, userName);            ResultSet set = state.executeQuery();            set.last();            int num = set.getRow();            if (num == 0) {                obj.put("code", ERROR);                obj.put("result", "用户名错误");            }            //这个就不必加else语句了,因为找不到相应的用户,所以下面的程序不会执行            PreparedStatement state1 =  conn.prepareStatement("select * from user where name=? and password=?");            state1.setString(1, userName);            state1.setString(2, password);            ResultSet set1 = state1.executeQuery();            set1.last();            int num1 = set1.getRow();            if (num1 == 1) {                obj.put("code", SUCCESS);                obj.put("result", "登录成功");            }        } catch (SQLException e) {            obj.put("code", FAIL);            obj.put("result", "登录失败");            e.printStackTrace();        }        return obj.toString();    }    /**     * 输出服务器数据库的所有内容     */    public String selectAll() {        JSONObject obj = new JSONObject();        Connection conn = SQLManager.newInstance().getConnection();        try {            PreparedStatement state = (PreparedStatement) conn.prepareStatement("select * from user");            ResultSet set = state.executeQuery();            set.first();            JSONArray array = new JSONArray();            while (!set.isAfterLast()) {                JSONObject item = new JSONObject();                item.put("username", set.getString("name"));                item.put("password", set.getString("password"));                array.add(item);                set.next();                obj.put("code", SUCCESS);                obj.put("message", "查询成功");                obj.put("data", array);            }        } catch (SQLException e) {            obj.put("code", FAIL);            obj.put("message", "查询失败");            e.printStackTrace();        }        return obj.toString();    }}

客户端代码

//主界面import java.awt.BorderLayout;import java.awt.EventQueue;import java.awt.event.ActionEvent;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 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.StatusLine;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.JButton;public class SignInDoPost 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 {                    SignInDoPost frame = new SignInDoPost();                    frame.setVisible(true);                } catch (Exception e) {                    e.printStackTrace();                }            }        });    }    /**     * Create the frame.     */    public SignInDoPost() {        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);        setBounds(100, 100, 445, 349);        contentPane = new JPanel();        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));        setContentPane(contentPane);        contentPane.setLayout(null);        textFieldName = new JTextField();        textFieldName.setBounds(131, 42, 156, 45);        contentPane.add(textFieldName);        textFieldName.setColumns(10);        textFieldPassword = new JTextField();        textFieldPassword.setBounds(131, 97, 156, 41);        contentPane.add(textFieldPassword);        textFieldPassword.setColumns(10);        JButton btnSignIn = new JButton("登录");        btnSignIn.setBounds(131, 157, 156, 23);        contentPane.add(btnSignIn);        btnSignIn.addActionListener(new ActionListener() {            @Override            public void actionPerformed(ActionEvent e) {                String userName = textFieldName.getText();                String password = textFieldPassword.getText();                String message=DoPostMethod.newInstance().signIn(userName, password);                System.out.println(message);            }        });        JButton btnRegister = new JButton("注册");        btnRegister.setBounds(131, 190, 156, 23);        contentPane.add(btnRegister);        btnRegister.addActionListener(new ActionListener() {            @Override            public void actionPerformed(ActionEvent e) {                EventQueue.invokeLater(new Runnable() {                    public void run() {                        try {                            RegisterDoPost frame = new RegisterDoPost();                            frame.setVisible(true);                        } catch (Exception e) {                            e.printStackTrace();                        }                    }                });            }        });        JButton btnUpdatePassword = new JButton("全部显示");        btnUpdatePassword.setBounds(131, 223, 156, 23);        contentPane.add(btnUpdatePassword);        btnUpdatePassword.addActionListener(new ActionListener() {            @Override            public void actionPerformed(ActionEvent e) {                String message=DoPostMethod.newInstance().selectAll();                System.out.println(message);            }        });    }}

这里写图片描述

//注册界面import java.awt.BorderLayout;import java.awt.EventQueue;import java.awt.event.ActionEvent;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 javax.swing.JFrame;import javax.swing.JPanel;import javax.swing.border.EmptyBorder;import javax.xml.crypto.dsig.keyinfo.KeyValue;import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.NameValuePair;import org.apache.http.StatusLine;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 javax.swing.JTextField;import javax.swing.JLabel;public class RegisterDoPost extends JFrame {    private JPanel contentPane;    private JTextField textFieldUserName;    private JTextField textFieldPassword;    public RegisterDoPost() {        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);        setBounds(100, 100, 438, 321);        contentPane = new JPanel();        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));        setContentPane(contentPane);        contentPane.setLayout(null);        JButton btnSignIn = new JButton("注册");        btnSignIn.setBounds(136, 144, 136, 23);        contentPane.add(btnSignIn);        btnSignIn.addActionListener(new ActionListener() {            @Override            public void actionPerformed(ActionEvent e) {                String userName = textFieldUserName.getText();                String password = textFieldPassword.getText();                String message=DoPostMethod.newInstance().register(userName, password);                System.out.println(message);            }        });        textFieldUserName = new JTextField();        textFieldUserName.setBounds(136, 52, 136, 36);        contentPane.add(textFieldUserName);        textFieldUserName.setColumns(10);        textFieldPassword = new JTextField();        textFieldPassword.setBounds(136, 98, 136, 36);        contentPane.add(textFieldPassword);        textFieldPassword.setColumns(10);        JLabel lblNewLabel = new JLabel("用户名");        lblNewLabel.setBounds(64, 62, 67, 15);        contentPane.add(lblNewLabel);        JLabel lblNewLabel_1 = new JLabel("密码");        lblNewLabel_1.setBounds(64, 108, 73, 15);        contentPane.add(lblNewLabel_1);    }}

这里写图片描述

//封装的方法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.StatusLine;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 DoPostMethod {    private DoPostMethod() {    }    private static DoPostMethod method;    public static synchronized DoPostMethod newInstance() {        if (method == null) {            method = new DoPostMethod();        }        return method;    }    /**     * 客户端注册方法     * @param userName  传递客户端的账户名     * @param password  传递客户端的密码     * @return  返回客户端读入的信息     */    public String register(String userName, String password) {        String urlString = "http://localhost:8080/MyServiceTest/MyTestServlet";        // 创建HttpClient对象        HttpClientBuilder builder = HttpClientBuilder.create();        // HttpClient        HttpClient client = builder.build();        // 设置延时时间        builder.setConnectionTimeToLive(30000, TimeUnit.MILLISECONDS);        JSONObject obj = new JSONObject();        obj.put("type", "register");        JSONObject data = new JSONObject();        data.put("username", userName);        data.put("password", password);        obj.put("data", data);        String json = obj.toString();        // 设置传入的数据        NameValuePair pair1 = new BasicNameValuePair("json", json);        // NameValuePair pair2 = new BasicNameValuePair("password",        // "123456");        ArrayList<NameValuePair> params = new ArrayList<>();        params.add(pair1);        // params.add(pair2);        try {            // 设置Post方法            HttpPost post = new HttpPost(urlString);            // 设置传递的参数格式            post.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));            post.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");            // 执行post方法获得服务器返回的所有数据            HttpResponse response = client.execute(post);            // HttpClient获得服务器返回的表头。            StatusLine statusLine = response.getStatusLine();            // 获得状态码            int code = statusLine.getStatusCode();            System.out.println(code);            if (code == HttpURLConnection.HTTP_OK) {                // 得到数据的实体。                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();//              JSONObject back = JSONObject.fromObject(s);//              int backCode = back.getInt("code");//              System.out.println(backCode);//              if (backCode == 0) {//                  String succ = back.getString("result");//                  System.out.println(succ);//              } else if (backCode == 1) {//                  String fall = back.getString("result");//                  System.out.println(fall);//              } else if (backCode == 2) {//                  String exists = back.getString("result");//                  System.out.println(exists);//              }            }        } catch (UnsupportedEncodingException e2) {            e2.printStackTrace();        } catch (UnsupportedOperationException e1) {            e1.printStackTrace();        } catch (IOException e1) {            e1.printStackTrace();        }        return null;    }    /**     * 客户端登录的方法     * @param userName  传递客户端输入的用户名     * @param password  传递客户端输入的密码     * @return     */    public String signIn(String userName, String password) {        String urlString = "http://localhost:8080/MyServiceTest/MyTestServlet";        // 创建HttpClient对象        HttpClientBuilder builder = HttpClientBuilder.create();        // HttpClient        HttpClient client = builder.build();        // 设置延时时间        builder.setConnectionTimeToLive(30000, TimeUnit.MILLISECONDS);        JSONObject obj = new JSONObject();        obj.put("type", "signin");        JSONObject data = new JSONObject();        data.put("username", userName);        data.put("password", password);        obj.put("data", data);        String json = obj.toString();        // 设置传入的数据        NameValuePair pair1 = new BasicNameValuePair("json", json);        // NameValuePair pair2 = new BasicNameValuePair("password",        // "123456");        ArrayList<NameValuePair> params = new ArrayList<>();        params.add(pair1);        // params.add(pair2);        try {            // 设置Post方法            HttpPost post = new HttpPost(urlString);            // 设置传递的参数格式            post.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));            post.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");            // 执行post方法获得服务器返回的所有数据            HttpResponse response = client.execute(post);            // HttpClient获得服务器返回的表头。            StatusLine statusLine = response.getStatusLine();            // 获得状态码            int code = statusLine.getStatusCode();            System.out.println(code);            if (code == HttpURLConnection.HTTP_OK) {                // 得到数据的实体。                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 e2) {            e2.printStackTrace();        } catch (UnsupportedOperationException e1) {            e1.printStackTrace();        } catch (IOException e1) {            e1.printStackTrace();        }        return null;    }    /**     * 查询服务器中指定数据库的所有内容     * @return     */    public String selectAll() {        String urlString = "http://localhost:8080/MyServiceTest/MyTestServlet";        // 创建HttpClient对象        HttpClientBuilder builder = HttpClientBuilder.create();        // HttpClient        HttpClient client = builder.build();        // 设置延时时间        builder.setConnectionTimeToLive(30000, TimeUnit.MILLISECONDS);        JSONObject obj = new JSONObject();        obj.put("type", "selectall");        String json = obj.toString();        // 设置传入的数据        NameValuePair pair1 = new BasicNameValuePair("json", json);        // NameValuePair pair2 = new BasicNameValuePair("password",        // "123456");        ArrayList<NameValuePair> params = new ArrayList<>();        params.add(pair1);        // params.add(pair2);        try {            // 设置Post方法            HttpPost post = new HttpPost(urlString);            // 设置传递的参数格式            post.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));            post.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");            // 执行post方法获得服务器返回的所有数据            HttpResponse response = client.execute(post);            // HttpClient获得服务器返回的表头。            StatusLine statusLine = response.getStatusLine();            // 获得状态码            int code = statusLine.getStatusCode();            System.out.println(code);            if (code == HttpURLConnection.HTTP_OK) {                // 得到数据的实体。                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 e2) {            e2.printStackTrace();        } catch (UnsupportedOperationException e1) {            e1.printStackTrace();        } catch (IOException e1) {            e1.printStackTrace();        }        return null;    }}

  本人较懒333,最后的客户端输入JSON解析没有写,命令结果显示在界面上也没有写╮(╯▽╰)╭
  最终效果…动态图太大没法显示,也是醉了。不是说好的2M么,怎么1.5M都传不了=。=,试了好多次终于是传上来了,不容易啊╮(╯▽╰)╭
  这里写图片描述
  
  

0 0
原创粉丝点击