Java Web implements user login function

1. Pure JSP method to implement user login function

(1) Implementation ideas

Login page login.jsp. After entering the user name and password, jump to the login processing page doLogin.jsp for business logic processing. If the login is successful, jump to the login success page success.jsp. Otherwise, jump to the login failure page. Page failure.jsp.
(2) Implementation steps

1. Create a Web project

  • CreateJava Enterpriseproject and add Web Application function
    Insert image description here
    Insert image description here

  • Set project name and save location
    Insert image description here

  • Click the [Finish] button

  • Modify the Artifact name in the project structure window -LoginDemo01
    Insert image description here

  • Edit the server configuration and redeploy the project
    Insert image description here

2. Create a login page

  • Login page - login.jsp
    Original code
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>用户登录</title>
</head>
<body>
<h3 style="text-align: center">用户登录</h3>
<form action="doLogin.jsp" method="post">
    <table border="1" cellpadding="10" style="margin: 0px auto">
        <tr>
            <td align="center">账号</td>
            <td><input type="text" name="username"/></td>
        </tr>
        <tr>
            <td align="center">密码</td>
            <td><input type="password" name="password"/></td>
        </tr>
        <tr align="center">
            <td colspan="2">
                <input type="submit" value="登录"/>
                <input type="reset" value="重置"/>
            </td>
        </tr>
    </table>
</form>
</body>
</html>

3. Create a login processing page

  • Login processing page - doLogin.jsp
    Original code
<%
    // 获取登录表单数据
    String username = request.getParameter("username");
    String password = request.getParameter("password");
    // 判断登录是否成功
    if (username.equals("易烊千玺") && password.equals("123456")) {
        // 跳转到登录成功页面,传递用户名
        response.sendRedirect("success.jsp?username=" + username);
    } else {
        // 跳转到登录失败页面,传递用户名
        response.sendRedirect("failure.jsp?username=" + username);
    }
%>

4. Create a login success page

  • Login success page - success.jsp
    Original code
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>登录成功</title>
</head>
<body>
<h3 style="text-align: center">恭喜,<%=request.getParameter("username")%>,登录成功!</h3>
</body>
</html>

5. Create a login failure page

  • Login failure page - failure.jsp
    Original code
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>登录失败</title>
</head>
<body>
<h3 style="text-align: center">遗憾,<%=request.getParameter("username")%>,登录失败!</h3>
</body>
</html>

6. Edit project homepage

  • Project homepage - index.jsp
    Original code
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>首页</title>
  </head>
  <body>
    <h1 style="color: red; text-align: center">纯JSP方式实现用户登录成功能</h1>
    <h3 style="text-align: center"><a href="login.jsp">跳转到登录页面</a></h3>
  </body>
</html>

(3) Test results

  • Start the server and display the home page
    Insert image description here

  • Click the [Jump to login page] hyperlink
    Insert image description here

  • Enter the correct username and password (Yi Yang Qianxi: 123456)
    Insert image description here

  • Click the [Login] button to jump to the login success page
    Insert image description here

  • Return to the login page and enter the wrong username or password
    Insert image description here

  • Click the [Login] button to jump to the login failure page
    Insert image description here

2. JSP+Servlet method to implement user login function

(1) Implementation ideas

  • In the login page login.jsp, after entering the user name and password, it jumps to the login handler LoginServlet for business logic processing. If the login is successful, it jumps to the login success page success.jsp. Otherwise, it jumps to the login failure page failure.jsp.

(2) Implementation steps

1. Create a Web project

  • BuildingJava EnterpriseItem, additionWeb ApplicationFunction
    Insert image description here

  • Set project name and save location
    Insert image description here

  • Click the [Finish] button

  • Modify the Artifact name in the project structure window -LoginDemo02
    Insert image description here

  • Edit the server configuration and redeploy the project
    Insert image description here

  • Switch to the [Server] tab
    Insert image description here

2. Create a login page

  • log in page -login.jsp
  • Original code
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
    <head>
        <title>用户登录</title>
    </head>
    <body>
        <h3 style="text-align: center">用户登录</h3>
        <form action="login" method="post">
            <table border="1" cellpadding="10" style="margin: 0px auto">
                <tr>
                    <td align="center">账号</td>
                    <td><input type="text" name="username"/></td>
                </tr>
                <tr>
                    <td align="center">密码</td>
                    <td><input type="password" name="password"/></td>
                </tr>
                <tr align="center">
                    <td colspan="2">
                        <input type="submit" value="登录"/>
                        <input type="reset" value="重置"/>
                    </td>
                </tr>
            </table>
        </form>
    </body>
</html>

3. Create a login handler

Create the net.xyx.serlvet package and create the LoginServletclass in the package

package net.xyx.servlet;

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 java.io.IOException;
import java.net.URLEncoder;

@WebServlet(name = "LoginServlet", urlPatterns = "/login")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 设置请求对象字符编码格式
        request.setCharacterEncoding("utf-8");
        // 获取登录表单数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        // 判断登录是否成功
        if (username.equals("无心剑") && password.equals("903213")) {
            // 采用重定向,跳转到登录成功页面
            response.sendRedirect("success.jsp?username=" + URLEncoder.encode(username, "utf-8"));
        } else {
            // 采用重定向,跳转到登录失败页面
            response.sendRedirect("failure.jsp?username=" + URLEncoder.encode(username, "utf-8"));
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }
}

4. Create a login success page

  • Login success page -success.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
    <head>
        <title>登录成功</title>
    </head>
    <body>
        <h3 style="text-align: center">恭喜,<%=request.getParameter("username")%>,登录成功!</h3>
    </body>
</html>

5. Create a login failure page

  • Login failure page -failure.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
    <head>
        <title>登录失败</title>
    </head>
    <body>
        <h3 style="text-align: center">遗憾,<%=request.getParameter("username")%>,登录失败!</h3>
    </body>
</html>

6. Edit project homepage

  • Project Home Page -index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
    <head>
        <title>首页</title>
    </head>
    <body>
        <h1 style="color: red; text-align: center">JSP+Servlet方式实现用户登录功能</h1>
        <h3 style="text-align: center"><a href="login.jsp">跳转到登录页面</a></h3>
    </body>
</html>

(3) Test results

  • Start the server and display the home page
    Insert image description here

  • Click the [Jump to login page] hyperlink
    Insert image description here

  • Enter the correct username and password (Yi Yang Qianxi: 001128)

  • Click the [Login] button to jump to the login success page
    Insert image description here

  • Return to the login page and enter the wrong username or password

  • Click the [Login] button to jump to the login failure page
    Insert image description here

3. JSP+Servlet+DB method to implement user login function

(1) Implementation ideas

Generally adopts MVC architecture. Login page login.jsp, after entering the user name and password, jumps to the login handler LoginServlet for business logic processing, calls the service layer, the service layer calls the data access layer (DAO), connects to the database, and queries the database to determine whether the login is successful. . If the login is successful, it will jump to the login success page success.jsp, otherwise it will jump to the login failure page failure.jsp.
MVC is the abbreviation of Model, View and Controller, which represent 3 responsibilities in web applications.

(2) Implementation steps

1. Create a database

Create database - test
Insert image description here

  • Click the [OK] button

2. Create user table

Create user table structure -t_user
Insert image description here

3. Create a Web project

  • Create a Java Enterprise project and add Web Application functionality
    Insert image description here

  • Set project name and save location
    Insert image description here

  • Click the [Finish] button

  • Modify the Artifact name in the project structure window -LoginDemo03
    Insert image description here

  • Edit the server configuration and redeploy the project
    Insert image description here

  • Switch to the [Server] tab

Insert image description here

4. Create user entity class

  • Create the net.xyx.bean package, and then create a User class in the package, corresponding to the user table (t_user), referred to as ORM
    Insert image description here
package net.xyx.bean;

import java.util.Date;

/**
 * 功能:用户实体类
 * 作者:xyx
 * 日期:2023年05月19日
 */
public class User {
    private int id;
    private String username;
    private String password;
    private String telephone;
    private Date registerTime;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getTelephone() {
        return telephone;
    }

    public void setTelephone(String telephone) {
        this.telephone = telephone;
    }

    public Date getRegisterTime() {
        return registerTime;
    }

    public void setRegisterTime(Date registerTime) {
        this.registerTime = registerTime;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", telephone='" + telephone + '\'' +
                ", registerTime=" + registerTime +
                '}';
    }
}

5. Add database driver

  • Create the lib directory under the WEB-INF directory and add the database driver
  • Add the database driver (jar package) to the project as a library

Insert image description here

Insert image description here

6. Create database connection management tool class

  • Create the net.xyx.dbutils package and create the ConnectionManagerclass in the package
    Insert image description here
package net.xyx.dbutils;

import javax.swing.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * 功能:数据库连接管理类
 * 作者:xyx
 * 日期:2020年06月05日
 */
public class ConnectionManager {
    private static final String DRIVER = "com.mysql.jdbc.Driver"; // 数据库驱动程序
    private static final String URL = "jdbc:mysql://localhost:3306/student/test?useSSL=false"; // 数据库统一资源标识符
    private static final String USER = "root"; // 数据库用户
    private static final String PASSWORD = "1"; // 数据库密码

    //私有化构造方法,拒绝实例化
    private ConnectionManager() {
    }

    /**
     * 获取数据库连接静态方法
     *
     * @return 数据库连接对象
     */
    public static Connection getConnection() {
        // 定义数据库连接
        Connection conn = null;

        try {
            // 安装数据库驱动程序
            Class.forName(DRIVER);
            // 获取数据库连接
            conn = DriverManager.getConnection(URL, USER, PASSWORD);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        // 返回数据库连接
        return conn;
    }

    /**
     * 关闭数据连接静态方法
     *
     * @param conn
     */
    public static void closeConnection(Connection conn) {
        // 判断数据库连接是否非空
        if (conn != null) {
            try {
                // 判断连接是否未关闭
                if (!conn.isClosed()) {
                    // 关闭数据库连接
                    conn.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 主方法:测试两个静态方法
     *
     * @param args
     */
    public static void main(String[] args) {
        // 获取数据库连接
        Connection conn = getConnection();
        // 判断数据库连接是否成功
        if (conn != null) {
            JOptionPane.showMessageDialog(null, "恭喜,数据库连接成功!");
        } else {
            JOptionPane.showMessageDialog(null, "遗憾,数据库连接失败!");
        }
        // 关闭数据库连接
        closeConnection(conn);
    }
}

7. Create user data access class

  • Create a sub-package in the net.xyx root package, and then create a class in the sub-packageUserDao
package net.xyx.dao;

import net.huawei.bean.User;
import net.huawei.dbutils.ConnectionManager;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 功能:用户数据访问类
 * 作者:xyx
 * 日期:2023年05月19日
 */
public class UserDao {
    /**
     * 用户登录方法
     * @param username
     * @param password
     * @return 用户对象(非空:登录成功,否则登录失败)
     */
    public User login(String username, String password) {
        // 声明用户对象
        User user = null;

        // 获取数据库连接
        Connection conn = ConnectionManager.getConnection();
        try {
            // 定义SQL字符串
            String strSQL = "SELECT * FROM t_user WHERE username = ? AND password = ?";
            // 创建预备语句对象
            PreparedStatement pstmt = conn.prepareStatement(strSQL);
            // 设置占位符
            pstmt.setString(1, username);
            pstmt.setString(2, password);
            // 执行查询,返回结果集
            ResultSet rs = pstmt.executeQuery();
            // 判断结果集是否为空
            if (rs.next()) {
                // 创建用户对象
                user = new User();
                // 利用当前记录字段值来设置用户对象属性
                user.setId(rs.getInt("id"));
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));
                user.setTelephone(rs.getString("telephone"));
                user.setRegisterTime(rs.getTimestamp("register_time"));
            }
        } catch (SQLException e) {
            System.err.println(e.getMessage());
        } finally {
            // 关闭数据库连接
            ConnectionManager.closeConnection(conn);
        }

        // 返回用户对象
        return user;
    }
}

8. Test user data access class

  • Create the test subclass in the net.xyx root package and create it in the subpackageTestUser
package net.xyx.test;

import net.xyx.bean.User;
import net.xyx.dao.UserDao;
import org.junit.Test;

/**
 * 功能:测试用户数据访问类
 * 作者:xyx
 * 日期:2023年05月19日
 */
public class TestUserDao {
    @Test
    public void testLogin() {
        String username = "无心剑";
        String password = "12345";

        // 创建用户数据访问对象
        UserDao userDao = new UserDao();
        // 调用登录方法,返回用户对象
        User user = userDao.login(username, password);
        // 判断用户登录是否成功
        if (user != null) { // 成功
            System.out.println("恭喜,用户[" + username + "]登录成功~");
        } else { // 失败
            System.out.println("遗憾,用户[" + username + "]登录失败~");
        }
    }
}

  • Modify the username and password and run the program again, prompting login failure.

4. Use MVC model to implement user registration function

1. Create a Web project

  • BuildingJava EnterpriseItem, additionWeb ApplicationFunction

Insert image description here

  • Set project name and save location
    Insert image description here
  • Modify the Artifact name in the project structure window -register
    Insert image description here
  • Edit the server configuration and redeploy the project
    Insert image description here

2. Create content

Insert image description here

  • front page
    Insert image description here
  • Registration interface
    Insert image description here
  • Subsequently, the corresponding interface will pop up if the registration is successful or failed.

Guess you like

Origin blog.csdn.net/qq_65584142/article/details/131145079