08-12 Serverlet 数据库连接、doPost方法 HttpClientDoGet HTTPClientDoPost

Serverlet 数据库连接、 doPost方法

//**数据库连接**
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;
    }

    public 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();
        }
    }
}

//**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 userName=request.getParameter("name");
        String passWord=request.getParameter("password");
        System.out.println("用户名:"+userName+"  密码:"+passWord);
        userName=Encoding.doEncoding(userName);
        passWord=Encoding.doEncoding(passWord);
        Connection connection=Mysqlmanger.newInstance().getConnection();

        try {
            PreparedStatement preparedStatement=connection.prepareStatement("select * from user where name=? and password=?");
            preparedStatement.setString(1, userName);
            preparedStatement.setString(2, passWord);
            ResultSet set=preparedStatement.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();
        }



        //显示在界面
        String s="用户名:"+userName+"  密码:"+passWord;
        response.setHeader("Content-type","text/html;charset=UTF-8");
        response.getWriter().append(s);
//      response.getWriter().append("Served at: ").append(request.getContextPath());
    }

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

}

//**前段与后台数据格式转换,避免乱码**
public class Encoding {
    public static String doEncoding(String string){
        try {
            byte[] array=string.getBytes("ISO-8859-1");
            string=new String(array, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return string;
    }
}

//**doPost方法**
public class DoPost extends JFrame {

    private JPanel contentPane;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    DoPost frame = new DoPost();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public DoPost() {
        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);

        JButton btnDopost = new JButton("doPost方法");
        btnDopost.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                String urlstring="http://localhost:8080/MyServerTest/MyServerlet";
                try {
                    URL url=new URL(urlstring);
                    HttpURLConnection httpconnect=(HttpURLConnection) url.openConnection();
                    httpconnect.setRequestMethod("POST");
                    //设置连接超时时间
                    httpconnect.setConnectTimeout(3000);
                    //读取超时时间
                    httpconnect.setReadTimeout(3000);
                    //设置接受的数据类型
                    httpconnect.setRequestProperty("Accept-Charset", "utf-8");
                    httpconnect.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                    httpconnect.setDoOutput(true);
                    httpconnect.setUseCaches(false);
                    String parmas="name=john&password=123";
                    httpconnect.getOutputStream().write(parmas.getBytes());
                    int code=httpconnect.getResponseCode();
                    System.out.println("HTTP 状态码"+code);
                    if(code==HttpURLConnection.HTTP_OK){
                        InputStream is=httpconnect.getInputStream();
                        InputStreamReader isr=new InputStreamReader(is);
                        BufferedReader br=new BufferedReader(isr);
                        String line=br.readLine();
                        while(line!=null){
                            System.out.println(line);
                            line=br.readLine();
                        }
                    }
                } catch (MalformedURLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }catch(SocketTimeoutException e){
                    System.out.println("连接服务器超时");
                }catch (ConnectException e){
                    System.out.println("服务器拒绝连接");
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });
        btnDopost.setBounds(117, 94, 125, 30);
        contentPane.add(btnDopost);
    }
}

HTTPClient

//**连接数据库**
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;
    }

    public 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();
        }
    }

}

//**前段与后台数据格式转换,避免乱码**
public class Encoding {
    public static String doEncoding(String string){
        try {
            byte[] array=string.getBytes("ISO-8859-1");
            string=new String(array, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return string;
    }
}

//**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 userName=request.getParameter("name");
        String passWord=request.getParameter("password");
        System.out.println("用户名:"+userName+"  密码:"+passWord);
        userName=Encoding.doEncoding(userName);
        passWord=Encoding.doEncoding(passWord);
        Connection connection=Mysqlmanger.newInstance().getConnection();

        try {
            PreparedStatement preparedStatement=connection.prepareStatement("select * from user where name=? and password=?");
            preparedStatement.setString(1, userName);
            preparedStatement.setString(2, passWord);
            ResultSet set=preparedStatement.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();
        }



        //显示在界面
        String s="用户名:"+userName+"  密码:"+passWord;
        response.setHeader("Content-type","text/html;charset=UTF-8");
        response.getWriter().append(s);
//      response.getWriter().append("Served at: ").append(request.getContextPath());
    }

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

}

//**HttpClientDoGet方法**

public class HttpClientDoGet extends JFrame {

    private JPanel contentPane;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    HttpClientDoGet frame = new HttpClientDoGet();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public HttpClientDoGet() {
        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);

        JButton button = new JButton("登录");
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String urlstring="http://localhost:8080/MyServerTest/MyServerlet?name=john&password=123";
                HttpClientBuilder builder=HttpClientBuilder.create();
                builder.setConnectionTimeToLive(3000, TimeUnit.MILLISECONDS);
                HttpClient httpClient=builder.build();
                HttpGet get=new HttpGet(urlstring);
                get.setHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
                try {
                    HttpResponse response=httpClient.execute(get);
                    StatusLine statusLine=response.getStatusLine();
                    int code=statusLine.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 (ClientProtocolException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }

            }
        });
        button.setBounds(120, 93, 123, 41);
        contentPane.add(button);
    }

}

//**HTTPClientDoPost方法**   
     //MyServerlet中Encoding就不必用了,不用担心乱码问题
public class HTTPClientDoPost extends JFrame {

    private JPanel contentPane;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    HTTPClientDoPost frame = new HTTPClientDoPost();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public HTTPClientDoPost() {
        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);

        JButton button = new JButton("登录");
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                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);
                NameValuePair pair1=new BasicNameValuePair("name", "john");
                NameValuePair pair2=new BasicNameValuePair("password", "123");
                ArrayList<NameValuePair> params=new ArrayList<>();
                params.add(pair1);
                params.add(pair2);
                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();
                        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(143, 80, 118, 45);
        contentPane.add(button);
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值