Use HttpServlet to implement simple login

1. Write the home page

I set two hyperlinks on the homepage to jump to the page, pointing to the login page and registration page respectively.

As shown below:

 The implementation code is as follows:

<html>
  <head>
    <title>Java Web</title>
  </head>
  <body>
    <a href="Login.jsp"><h2>去登录</h2></a>
    <a href="Enroll.jsp"><h2>去注册</h2></a>
  </body>
</html>

2. Write a login page

In the login page, we need to use JDBC to connect to the database for data query operations (to determine whether the account and password entered by the user are correct)

First let’s write the login page

as the picture shows:

 

 The implementation code is as follows:

<%--
  Created by IntelliJ IDEA.
  User: DELL
  Date: 2023/2/14
  Time: 11:03
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%--<h2>登录</h2>
<form action="login" method="post">
    账号:<input type="text" name="user"><br>
    密码:<input type="password" name="pwd"><br>
    <input type="submit" value="登录">
</form>--%>
<html>
    <head>
        <title>Java Web</title>
    </head>
    <body>
        <h2>登录</h2>
        <form action="login" method="post">
            账号:<input type="text" name="user"><br>
            密码:<input type="password" name="pwd"><br>
        <input type="submit" value="登录">
        </form>
    </body>
</html>

3. Write the registration page

In the registration page, we need to use JDBC to connect to the database to add data (obtain the data in the request sent by the browser through servlet and add it to the database)

Before adding data, let us first complete the writing of the registration page.

as the picture shows:

 4. Determine whether you have the account

We need to determine whether the account exists in the database. If there is such an account, it will prompt that the login is successful. If there is no such account, it will prompt that the login failed.

If I want to implement this function, I will divide it into the following steps:

1. Get user-submitted data from the request

2. Perform query operations in the database based on the account and password submitted by the user. At this time we need to use JDBC to connect to the database.

3. If the account exists in the database, it will prompt successful login. If there is no such account, it will prompt failed login.

The implementation code is as follows:

/**
 * 登录类
 */
public class Login extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("Login...get");
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("Login...post");
        //1.从请求中获取用户提交的参数(数据)
        request.setCharacterEncoding("UTF-8");//设置请求的编码格式为中文
        String user = request.getParameter("user");//根据表单的name属性获取用户输入的值
        String pwd = request.getParameter("pwd");//根据表单的name属性获取用户输入的值

        System.out.println(user);
        System.out.println(pwd);
        Connection con = null;
        PreparedStatement pstm = null;
        ResultSet rs = null;
        //2.根据用户提交的用户名和密码---去数据库执行查询
        try {
            //2.1 加载驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            //2.2 获取连接
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/users?useSSL=false&serverTimezone=UTC", "root", "123456");
            //2.3 编写SQL语句
            String sql = "select * from users where user=? and pwd=?";
            //2.4 预处理SQL语句对象
            pstm = con.prepareStatement(sql);
            //2.5 给?赋值
            pstm.setObject(1,user);
            pstm.setObject(2,pwd);
            System.out.println(user);
            System.out.println(pwd);
            //2.6 获取数据
            rs = pstm.executeQuery();
            //2.7 设置响应的编码格式为UTF-8格式
            response.setCharacterEncoding("UTF-8");
            //2.8 设置以文本或网页的形式响应
            response.setContentType("text/html;charset=UTF-8");
            //2.9 判断是否有数据,做出响应
            if (rs.next()){
                //登录成功
                response.getWriter().write("登录成功!");//使用字符集给前端做出响应
            }else {
                //登录失败
                response.getWriter().write("账号不存在或密码错误!");
            }
        } catch (ClassNotFoundException | SQLException e) {
            throw new RuntimeException(e);
        }finally {
            //3. 关闭资源
            try {
                //判断rs是否为空,如果不为空则关闭资源
                if (rs!=null){
                    rs.close();
                }
                //判断pstm是否为空,如果不为空则关闭资源
                if (pstm!=null){
                    pstm.close();
                }
                //判断con是否为空,如果不为空则关闭资源
                if (con!=null){
                    con.close();
                }
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

 

5. Add account

To add an account, we need to add data to the database (obtain the registration information submitted by the user from the request and then

Add the obtained registration information to the database through JDBC)

If I want to implement this function, I will divide it into the following steps:

1. Get user-submitted data from the request

2. Add the registration information submitted by the user to the database

The implementation code is as follows:

/**
 * 注册类
 */
public class Enroll extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("enroll...get");
        //调用doPost方法
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("enroll...post");
        //设置请求的编码格式为UTF-8格式
        request.setCharacterEncoding("UTF-8");
        //1. 从请求中获取用户提交的注册参数(数据)
        String zhangh = request.getParameter("zhangh");
        String pwd = request.getParameter("pwd1");
        //2. 通过JDBC把获取到的注册信息添加到数据库中
        Connection con = null;
        PreparedStatement pstm = null;
        try {
            //2.1 加载驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            //2.2 获取连接
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/users?useSSL=false&serverTimezone=UTC", "root", "123456");
            //2.3 编写SQL语句
            String sql = "insert into users (user,pwd) values (?,?)";
            //2.4 预处理SQL语句对象
            pstm = con.prepareStatement(sql);
            //2.5 给?赋值
            pstm.setObject(1,zhangh);
            pstm.setObject(2,pwd);
            //2.6 执行SQl语句返回受影响的行数
            int i = pstm.executeUpdate();
            //2.7 设置响应的编码格式为UTF-8格式
            response.setCharacterEncoding("UTF-8");
            //2.8 设置以文本或网页的形式响应
            response.setContentType("text/html;charset=UTF-8");//已什么样的格式(文本/网页)响应
            //2.9 判断影响行数是否大于零,大于零表示添加数据成功,反之添加数据失败,做出响应
            if (i>0){
                //注册成功
                response.getWriter().write("注册成功!");//使用字符集给前端做出响应
            }else {
                //注册失败
                response.getWriter().write("注册失败!");//使用字符集给前端做出响应
            }
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            //3. 关闭资源
            try {
                //判断pstm是否为空,如果不为空则关闭资源
                if (pstm!=null){
                    pstm.close();
                }
                //判断con是否为空,如果不为空则关闭资源
                if (con!=null){
                    con.close();
                }
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

6. Configure the servlet class

Configure the servlet class in .xml to handle requests

The implementation code is as follows:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    <!--配置Servlet类-->
    <servlet>
        <!-- 起别名 -->
        <servlet-name>login</servlet-name>
        <!-- servlet类所在的位置:类的全类名就是 包名.类名 -->
        <servlet-class>com.http.Servlet.Login</servlet-class>
    </servlet>
    <!-- Servlet类的映射:Servlet用来处理哪个请求 -->
    <servlet-mapping>
        <servlet-name>login</servlet-name>
        <url-pattern>/login</url-pattern>
    </servlet-mapping>

    <servlet>
        <servlet-name>enroll</servlet-name>
        <servlet-class>com.http.Servlet.Enroll</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>enroll</servlet-name>
        <url-pattern>/enroll</url-pattern>
    </servlet-mapping>
</web-app>

Guess you like

Origin blog.csdn.net/m0_71385552/article/details/129045492