Servlet+JSP+MySQL realizes user login and registration

Servlet+JSP+MySQL realizes user login and registration

Use servlet+jsp+mysql to implement a simple user login and registration case.



foreword

When you are learning javaweb, it is essential to interact with the database. Here we use a common login and registration case to realize a simple interaction with the mysql database.


train of thought

The front-end (JSP) page submits the form data (sends the request to the Servlet) to the Servlet, and the Servlet obtains the request content and executes the registration or login method according to the method parameter. User registration is to store the data entered by the user in the database. When the user logs in, the data entered by the user is compared with the data in the database. If the comparison is successful, the user logs in.

Prepare

The required jar package:

jsp-api.jar
servlet-aip.jar
c3p0-0.9.1.2.jar
commons-dbutils-1.6.jar
mysql-connector-java-8.0.19.jar

1. Quick start

1. Create a database

Create a database s_user, and create a user table structure in s_user
:

CREATE DATABASE IF NOT EXISTS `s_user`;
USE `s_user`;
CREATE TABLE IF NOT EXISTS `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '用户名',
  `password` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '密码',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;

INSERT INTO `user` (`id`, `username`, `password`) VALUES
	(1, 'user1', '123456'),

2. Connect to the database

Here we use c3p0 to connect to the database.
Create a new c3p0-config.xml file in the src directory
and write the following content in it:

<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
	<default-config>
		<property name="driverClass">com.mysql.cj.jdbc.Driver</property>
		<property name="jdbcUrl">jdbc:mysql://localhost:3306/s_user?serverTimezone=Asia/Shanghai&amp;useSSL=false</property>
		<property name="user">root</property>
		<property name="password">你的数据库密码</property>
	</default-config>
</c3p0-config>

Create a new tools folder, and create a MySQLTools tool class in it to operate the database.

code show as below:

/**
 * 数据库工具类
 */
public class MySQLTools {
    
    
    private static ComboPooledDataSource dataSource = null;

    private static ThreadLocal<Connection> tl = new ThreadLocal<Connection>();

    //1.加载配置文件
    // 2.创建DataSource
    static {
    
    
        dataSource = new ComboPooledDataSource();
    }

    public static DataSource getDataSource(){
    
    
        return dataSource;
    }

    public static Connection getConnection(){
    
    
        Connection conn = tl.get();
        try {
    
    
            if(conn == null){
    
    
                conn = dataSource.getConnection();
            }
        } catch (SQLException e) {
    
    
            e.printStackTrace();
        }
        tl.set(conn);
        return conn;
    }

    /**
     * 开始事务
     * @throws SQLException
     */
    public static void startTransaction(){
    
    
        Connection conn = getConnection();
        try {
    
    
            conn.setAutoCommit(false);
        } catch (SQLException e) {
    
    
            e.printStackTrace();
        }
    }

    /**
     * 回滚事务
     * @throws SQLException
     */
    public static void rollback(){
    
    
        Connection conn = getConnection();
        try {
    
    
            conn.rollback();
        } catch (SQLException e) {
    
    
            e.printStackTrace();
        }

    }

    /**
     * 提交事务
     * @throws SQLException
     */
    public static void commit(){
    
    
        Connection conn = getConnection();
        try {
    
    
            conn.commit();
        } catch (SQLException e) {
    
    
            e.printStackTrace();
        }
    }

    /**
     * 关闭Connection,并移除线程中的连接
     * @throws SQLException
     */
    public static void closeConnection(){
    
    
        close(getConnection());
        tl.remove();
    }

    public static void close(Connection conn){
    
    
        try {
    
    
            if(conn != null){
    
    
                conn.close();
            }
        } catch (SQLException e) {
    
    
            e.printStackTrace();
        }
    }

    public static void close(Statement stm){
    
    
        try {
    
    
            if(stm != null){
    
    
                stm.close();
            }
        } catch (SQLException e) {
    
    
            e.printStackTrace();
        }
    }

    public static void close(ResultSet rs){
    
    
        try {
    
    
            if(rs != null){
    
    
                rs.close();
            }
        } catch (SQLException e) {
    
    
            e.printStackTrace();
        }
    }

3. Create an entity class userBean

code show as below:

public class userBean {
    
    
    private int id;
    private String username;
    private String password;

    public int getId() {
    
    
        return id;
    }

    public String getUsername() {
    
    
        return username;
    }

    public String getPassword() {
    
    
        return password;
    }

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

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

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

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

4. Create a service layer

Create a userService class under service

code show as below:

public interface userService {
    
    
    //注册
    void register(userBean user) throws SQLException;
    //登录
    Boolean login(userBean user) throws SQLException;
}

Then create the impl folder under the service folder, and create userServiceimpl under the impl to inherit userService

code show as below:

public class userServiceImpl implements userService {
    
    
    userDao userDao = new userDaoImpl();

    //注册方法
    @Override
    public void register(userBean user) throws SQLException {
    
    
        userDao.register(user);
    }
    
    //登录方法
    @Override
    public Boolean login(userBean user) throws SQLException {
    
    
        userBean userBean = userDao.login(user);
        System.out.println(userBean);
        if (userBean == null){
    
     //用户不存在
            return false;
        }
        return true;
    }

5. Create dao layer

Create the userDao class under dao

code show as below:

public interface userDao {
    
    
    //注册
    void register(userBean user) throws SQLException;

    //登录
    userBean login(userBean user) throws SQLException;
}

Then create the impl folder under the dao folder, and create userDaoimpl under the impl to inherit userDao

code show as below:

public class userDaoImpl implements userDao {
    
    

    QueryRunner queryRunner = new QueryRunner(MySQLTools.getDataSource());

    //数据库操作把用户名密码插入到mysql中
    @Override
    public void register(userBean user) throws SQLException {
    
    
        queryRunner.update("INSERT INTO user VALUES(?,?,?)",null,user.getUsername(),user.getPassword());
    }

    //用户名密码对比
    @Override
    public userBean login(userBean user) throws SQLException {
    
    
        return queryRunner.query("SELECT * FROM user WHERE username = ? AND password = ?",new BeanHandler<userBean>(userBean.class),user.getUsername(),user.getPassword());
    }

6. Create Servlet

Create a userServlet class under the servlet to inherit HttpServlet, add the @WebServlet annotation, and write the doPost and doGet methods in the class

code show as below:

@WebServlet(name = "user",urlPatterns = "/user")
public class userServlet extends HttpServlet {
    
    

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

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

}

In development, we often need to process multiple requests in a Servlet. It is too inefficient to use if layer by layer loop, so we can optimize it and use java reflection to generate multiple request problems. This code can continue to be optimized, and I will not discuss it here. Too much description.

Write in doPost:

code show as below:

        //指定一个方法名,找到这个方法并直接调用
        //获取调用的方法名称
        String method = request.getParameter("method");
        System.out.println(method);
        try {
    
    
            // getDeclaredMethod(方法名,参数列表(传的是各个参数的类))
            // 通过反射找到该方法并调用
            Method declaredMethod = this.getClass().getDeclaredMethod(method, HttpServletRequest.class, HttpServletResponse.class);
            System.out.println(declaredMethod);
            // 把方法权限设大
            declaredMethod.setAccessible(true);
            // invoke(对象,参数) 执行该方法
            declaredMethod.invoke(this,request,response);
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
    
    
            e.printStackTrace();
        }

Login method:

code show as below:

 //登录
    private void login(HttpServletRequest request, HttpServletResponse response) throws IOException, SQLException, ServletException {
    
    
        userBean userBean = new userBean();
        //获取表单数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        userBean.setUsername(username);
        userBean.setPassword(password);
        //验证
        if(!userService.login(userBean)){
    
     //登录失败
            //转发
            request.getRequestDispatcher("err.jsp").forward(request, response);
        }
        request.getRequestDispatcher("loginsuccess.jsp").forward(request, response);
    }

Registration method:

code show as below:

 //注册
    private void register(HttpServletRequest request, HttpServletResponse response) throws IOException, SQLException, ServletException {
    
    
        userBean userBean = new userBean();
        //获取表单数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String password1 = request.getParameter("password1");
        //判断密码是否相等
        if(!password1.equals(password)){
    
    
            response.setContentType("text/html");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write("两次输入密码不一致");
        }else {
    
     //注册成功
            userBean.setUsername(username);
            userBean.setPassword(password);
            userService.register(userBean);
            request.getRequestDispatcher("regsuccess.jsp").forward(request, response);
        }
    }

Full code:

code show as below:

@WebServlet(name = "user",urlPatterns = "/user")
public class userServlet extends HttpServlet {
    
    

    userService userService = new userServiceImpl();
    protected void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
    
    
        //反射:你指定一个方法名,我找到这个方法并直接调用)
        //获取调用的方法名称
        String method = request.getParameter("method");
        System.out.println(method);
        try {
    
    
            // getDeclaredMethod(方法名,参数列表(传的是各个参数的类))
            // 通过反射找到该方法并调用
            Method declaredMethod = this.getClass().getDeclaredMethod(method, HttpServletRequest.class, HttpServletResponse.class);
            System.out.println(declaredMethod);
            // 把方法权限设大
            declaredMethod.setAccessible(true);
            // invoke(对象,参数) 执行该方法
            declaredMethod.invoke(this,request,response);
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
    
    
            e.printStackTrace();
        }

    }

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

    //注册
    private void register(HttpServletRequest request, HttpServletResponse response) throws IOException, SQLException, ServletException {
    
    
        userBean userBean = new userBean();
        //获取表单数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String password1 = request.getParameter("password1");
        //判断密码是否相等
        if(!password1.equals(password)){
    
    
            response.setContentType("text/html");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write("两次输入密码不一致");
        }else {
    
     //注册成功
            userBean.setUsername(username);
            userBean.setPassword(password);
            userService.register(userBean);
            request.getRequestDispatcher("regsuccess.jsp").forward(request, response);
        }
    }

    //登录
    private void login(HttpServletRequest request, HttpServletResponse response) throws IOException, SQLException, ServletException {
    
    
        userBean userBean = new userBean();
        //获取表单数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        userBean.setUsername(username);
        userBean.setPassword(password);
        //验证
        if(!userService.login(userBean)){
    
     //登录失败
            //转发
            request.getRequestDispatcher("err.jsp").forward(request, response);
        }
        request.getRequestDispatcher("loginsuccess.jsp").forward(request, response);
    }

7. Create a front-end jsp page

At this point, our background code is over, and the next step is our front page. Because it is used for testing, it is written a little crudely.

register.jsp:

code show as below:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no">
    <title>注册</title>
</head>
<body>
<div class="container" style="margin: auto">
    <form action="/user?method=register" method="post">
    <div class="tit">注册</div>
    <input type="text" name="username" placeholder="账号"><br><br>
    <input type="password" name="password" placeholder="密码"><br><br>
    <input type="password" name="password1" placeholder="确认密码"><br>
    <input type="submit" value="注册">
    </form>
    <span>已有账号?<a href="login.jsp">去登录</a></span>
</div>
</body>
</html>

login.jsp:

code show as below:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no">
    <title>登录</title>
</head>
<body>
<div class="container" style="height: 600px;width: 600px;margin: auto 0">
    <form action="/user?method=login" method="post">
    <div class="tit">登录</div><br>
    <input type="text" name="username" placeholder="账号"><br><br>
    <input type="password" name="password" placeholder="密码"><br>
    <input type="submit" value="登录">
    </form>
    <span>没有账号?<a href="register.jsp">去注册</a></span>
</div>
</body>
</html>

Other pages are similar, such as the successful registration page, you can use it freely.

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<span>注册成功!<a href="login.jsp">返回登录</a></span>
</body>
</html>

project structure
insert image description here

8. Test

register

insert image description here
Registration succeeded
insert image description here
View database
insert image description here
Registration failed
insert image description here

Log in

Login succeeded
insert image description here
Login failed
insert image description here
In this way, we have completed the simple login and registration function!

Summarize

The above is what I want to talk about today. This article only briefly introduces a simple login and registration case of servlet+jsp and mysql. You can create better-looking and better projects based on this idea. Everyone is constantly growing and growing. There will inevitably be some stumbles on the road, and it is in such an environment that we can hone ourselves. Today's content is over, thank you all. If you have any other questions, please ask me! Friends who need the source code pay attention to the official account "Junjun's Notes", and send it to everyone for free!
insert image description here

Guess you like

Origin blog.csdn.net/weixin_46721191/article/details/130245674