08-13 登錄、註冊, 數據庫連接

登錄、註冊, 數據庫連接

//**com.client**
   //**Login**
   public class Login 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 {
                    Login frame = new Login();
                    frame.setTitle("登錄");
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public Login() {
        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(100, 10, 162, 34);
        contentPane.add(textField);
        textField.setColumns(10);

        textField_1 = new JTextField();
        textField_1.setBounds(100, 63, 162, 34);
        contentPane.add(textField_1);
        textField_1.setColumns(10);

        JButton btnLogin = new JButton("Login");
        btnLogin.setBounds(122, 123, 112, 34);
        btnLogin.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                String message=MyHttpMethod.newInstance().Login(textField.getText(), textField_1.getText());
                System.out.println(message);
            }
        });
        contentPane.add(btnLogin);

        JLabel lblName = new JLabel("Name");
        lblName.setBounds(21, 19, 54, 15);
        contentPane.add(lblName);

        JLabel lblPassward = new JLabel("Passward");
        lblPassward.setBounds(21, 72, 69, 15);
        contentPane.add(lblPassward);

        JButton btnRegister = new JButton("Register");
        btnRegister.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                EventQueue.invokeLater(new Runnable() {
                    public void run() {
                        try {
                            Register frame = new Register();
                            frame.setTitle("註冊");
                            frame.setVisible(true);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        });
        btnRegister.setBounds(278, 12, 101, 28);
        contentPane.add(btnRegister);

        JButton btnForget = new JButton("Forget");
        btnForget.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
            }
        });
        btnForget.setBounds(278, 65, 101, 28);
        contentPane.add(btnForget);

        JButton btnLogout = new JButton("Logout");
        btnLogout.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String message=MyHttpMethod.newInstance().Logout(textField.getText(), textField_1.getText());
                System.out.println(message);
            }
        });
        btnLogout.setBounds(257, 129, 101, 28);
        contentPane.add(btnLogout);
    }
}
   //**Register**
   public class Register extends JFrame {

    private JPanel contentPane;
    private JTextField textField;
    private JTextField textField_1;
    private JTextField textField_2;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {

    }

    /**
     * Create the frame.
     */
    public Register() {
        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(130, 25, 171, 33);
        contentPane.add(textField);
        textField.setColumns(10);

        textField_1 = new JTextField();
        textField_1.setBounds(130, 90, 171, 33);
        contentPane.add(textField_1);
        textField_1.setColumns(10);

        JButton btnRegister = new JButton("Register");
        btnRegister.setBounds(138, 207, 114, 33);
        btnRegister.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {             
                    String message=MyHttpMethod.newInstance().Register(textField.getText(), textField_1.getText(), textField_2.getText());
                    System.out.println(message);                        
            }
        });
        contentPane.add(btnRegister);

        JLabel lblName = new JLabel("Name");
        lblName.setBounds(23, 34, 76, 15);
        contentPane.add(lblName);

        JLabel lblPassword = new JLabel("Password");
        lblPassword.setBounds(23, 99, 76, 15);
        contentPane.add(lblPassword);

        textField_2 = new JTextField();
        textField_2.setBounds(130, 146, 171, 33);
        contentPane.add(textField_2);
        textField_2.setColumns(10);

        JLabel lblRepassword = new JLabel("Repassword");
        lblRepassword.setBounds(23, 155, 97, 15);
        contentPane.add(lblRepassword);

        JButton btnSelect = new JButton("Select");
        btnSelect.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String message=MyHttpMethod.newInstance().Select();
                System.out.println(message);
            }
        });
        btnSelect.setBounds(279, 207, 97, 33);
        contentPane.add(btnSelect);
    }
}

//**com.http**
   //**MyHttpManager**
   public class MyHttpManager {
    private static MyHttpManager myHttpManager;
    public static synchronized MyHttpManager newInstance(){
        if(myHttpManager==null){
            myHttpManager=new MyHttpManager();
        }
        return myHttpManager;
    }
    private MyHttpManager(){

    }
}
   //**MyHttpMethod**
   public class MyHttpMethod {
    private static MyHttpMethod manager;
    public static synchronized MyHttpMethod newInstance(){
        if(manager==null){
            manager=new MyHttpMethod();
        }
        return manager;
    }

    //註冊的方法
    public String Register(String name,String password,String repassword){
        String urlstring="http://localhost:8080/MyServerTest//MyServerlet";
        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");
        JSONObject date=new JSONObject();
        date.put("name", name);
        date.put("password", password);
        date.put("repassword", repassword);
        obj.put("date", date);
        NameValuePair pair=new BasicNameValuePair("json", obj.toString());

        ArrayList<NameValuePair> params=new ArrayList<>();
        params.add(pair);

        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);

                    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 "";
    }

    //登錄的方法
    public String Login(String name,String password){
        String urlstring="http://localhost:8080/MyServerTest//MyServerlet";
        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");
        JSONObject date=new JSONObject();
        date.put("name", name);
        date.put("password", password);
        obj.put("date", date);
        NameValuePair pair=new BasicNameValuePair("json", obj.toString());

        ArrayList<NameValuePair> params=new ArrayList<>();
        params.add(pair);

        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);

                    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 "";
    }

    //註銷的方法
    public String Logout(String name,String password){
        String urlstring="http://localhost:8080/MyServerTest//MyServerlet";
        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", "logout");
        JSONObject date=new JSONObject();
        date.put("name", name);
        date.put("password", password);
        obj.put("date", date);
        NameValuePair pair=new BasicNameValuePair("json", obj.toString());

        ArrayList<NameValuePair> params=new ArrayList<>();
        params.add(pair);

        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);

                    line=br.readLine();
                }
                return buffer.toString();
            }
        } 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();
        }
        return "";
    }

    //查詢的方法
    public String Select(){
        String url="http://localhost:8080/MyServerTest//MyServerlet";
        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 pair=new BasicNameValuePair("json", obj.toString());
        ArrayList<NameValuePair> params=new ArrayList<>();
        params.add(pair);
        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);
                    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 "";
    }

}


//**com.serverlet**
   //**Mysqlmanger**
   public class Mysqlmanger {
    private Statement statement;
    private Connection connection;

    public Connection getConnection() {
        return connection;
    }
    public void setConnection(Connection connection) {
        this.connection = connection;
    }
    public Statement getStatement() {
        return statement;
    }
    public void setStatement(Statement statement) {
        this.statement = statement;
    }

    private static Mysqlmanger manger;
    public static synchronized Mysqlmanger newInstance(){
        if(manger==null){
            manger=new Mysqlmanger();
        }
        return manger;
    }

    private Mysqlmanger(){
         //連接數據庫驅動
        String driver="com.mysql.jdbc.Driver";
        //URL指向要訪問的數據庫名
        String url="jdbc:mysql://localhost:3306/clazz";
        //MySQL配置時的用戶名
        String user="root";
        //Java連接MySQL配置時的密碼
        String  password="123456";

        try {
            Class.forName(driver);
            connection=DriverManager.getConnection(url, user, password);
            if(!connection.isClosed()){
                statement=connection.createStatement();
                String create="create table if not exists user(id int not null primary key auto_increment ,name varchar(30) not null,password varchar(30) not null)";
                statement.execute(create);
//              System.out.println("user表創建成功");
            }else{
                System.out.println("請打開數據庫");
            }
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
   //**SqlMethod**
   public class SqlMethod {
    private Connection connection;

    public Connection getConnection() {
        return connection;
    }

    public void setConnection(Connection connection) {
        this.connection = connection;
    }

     private static SqlMethod sqlMethod;
    public static synchronized SqlMethod newInstance(){
        if(sqlMethod==null){
            sqlMethod=new SqlMethod();
        }
        return sqlMethod;
    }

    //登錄操作
        public String Login(String name,String password){
            connection=Mysqlmanger.newInstance().getConnection();
            String string="";
            try {
                if(!connection.isClosed()){
                    PreparedStatement state=connection.prepareStatement("select * from user where name=? and password=?");
                    state.setString(1, name);
                    state.setString(2, password);
                    ResultSet set=state.executeQuery();
                    set.last();
                    int num=set.getRow();
                    System.out.println("查詢結果"+num);
                    if(num==1){
                        string="登錄成功";
                        return string;
                    }else{
                        string="用戶名或密碼錯誤";
                        return string;
                    }

                }
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return string;
        }


        //註冊操作
        public String Register(String name,String password,String repassword){
            Statement state=Mysqlmanger.newInstance().getStatement();
            String sql="select * from user where name='"+name+"'";
            String string="";
            try {
                ResultSet set = state.executeQuery(sql);
                set.last();//設置遊標,放到最後一行
                int num=set.getRow();//得到最後一行在第幾行
                System.out.println("查詢結果: "+num);
                if(num>0){
                    string="該用戶已存在";
                    return string;
                }else{
                    if(!password.equals(repassword)){
                        string="密碼不一致";
                        return string;
                    }
                    if(name.equals("")||password.equals("")){
                        string="用戶名或密碼不能爲空";
                        return string;  
                    }
                    String register="insert into user(name,password)values('"
                +name+"','"
                +password
                +"')";
                state.execute(register);
                string="註冊成功";
                return string;
                }

            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            return string;
        }

        //註銷操作
        public String Logout(String name,String password){
            connection=Mysqlmanger.newInstance().getConnection();
            String string="";
            if(name.equals("")||password.equals("")){
                string="用戶名或密碼不能爲空";
                return string;
            }else{
                try {
                    if(!connection.isClosed()){
                        PreparedStatement state=connection.prepareStatement("select * from user where name=? and password=?");
                        state.setString(1, name);
                        state.setString(2, password);
                        ResultSet set=state.executeQuery();
                        set.last();
                        int num=set.getRow();
                        System.out.println("查詢結果"+num);
                        if(num==1){
                            String delete="delete from user where name='"+name+"'";
                            state.execute(delete);
                            string="刪除成功";
                            return string;
                        }else{
                            string="該用戶不存在";
                            return string;
                        }

                    }

                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }


            return string;
        }

        //查詢操作
        public String   select(){
            JSONObject obj=new JSONObject();
            Connection conn=Mysqlmanger.newInstance().getConnection();
            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("name", set.getString("name"));
                    item.put("password",set.getString("password"));                 
                    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();
        }

    }

   //**MyServerlet**


   /**
 * Servlet implementation class MyServerlet
 */
@WebServlet("/MyServerlet")
public class MyServerlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public MyServerlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //顯示在控制檯
        String json=request.getParameter("json");
        System.out.println("得到的數據"+json);
        JSONObject obj=JSONObject.fromObject(json);
        String type=obj.getString("type");
        String string="";
        if(type.equals("login")){
            String name=obj.getJSONObject("date").getString("name");
            String password=obj.getJSONObject("date").getString("password");            
            string=SqlMethod.newInstance().Login(name, password);
        }

        if(type.equals("register")){
            String name=obj.getJSONObject("date").getString("name");
            String password=obj.getJSONObject("date").getString("password");
            String repassword=obj.getJSONObject("date").getString("repassword");

            string=SqlMethod.newInstance().Register(name, password,repassword);                         
        }

        if(type.equals("logout")){
            String name=obj.getJSONObject("date").getString("name");
            String password=obj.getJSONObject("date").getString("password");            

            string=SqlMethod.newInstance().Logout(name, password);              
        }

        if(type.equals("select")){
            string=SqlMethod.newInstance().select();            
        }

        response.setHeader("Content-type","text/html;charset=UTF-8");           
        response.getWriter().append(string);


    }

    /**
     * @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);
    }

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章