使用JSP+Servlet+MySQL实现登录注册功能

✅作者简介:大家好,我是Leo,热爱java后端开发者,一个想要与大家共同进步的男人😉😉
🍎个人主页:Leo的博客
💞当前专栏: Java从入门到精通
✨特色专栏: mysql学习
🥭本文内容:使用JSP+servlet+MySQL实现登录注册功能
📚个人知识库: Leo知识库,欢迎大家访问

1.前言

大家好,我是Leo哥🫣🫣🫣,前几天一个在大学的粉丝跟我说:Leo哥,我们最近要搞那个Java期末作业,要求是通过Javaweb知识点,使用JDBC,MySQL,JSP,Servlet等技术实现一个登录和注册功能,能不能出一期教程啊,老师啥也不教。听到这里我也是感触颇深,让我看到我之前的影子,当时老师也是啥都不教,就念个PPT,啥都要咱们自己琢磨。既然这样,咱们就出一期保姆级教程。后面也会出一些demo案例放到这个系列,第一期就先来点简单的开胃菜吧好了,话不多说让我们开始吧😎😎😎。

2.环境配置

首先Leo哥这里先声明一下本次教程的环境配置哈,大家可以跟我横向对比。

因为是比较基础的一篇,考虑到做期末作业,没有接触到Maven,所以我们这里就还是使用原生jar包的方式哈。

环境:

  • Intellij IDEA 2023
  • MySQL8.0
  • Tomcat 8.5
  • JDK8
  • JDBC
  • Navicat 16

3.项目创建

首先我会带大家从零创建一个JavaWeb项目,然后进行环境测试没问题之后,我们再继续往下进行。

打开IDEA,File — New — Project进行创建

开始创建项目,这里我们直接进模块创建。

查看我们的项目结构,并引入MySQL依赖

添加Tomcat依赖

配置Tomcat服务器

首先点击IDEA,最上面,点击Edit Configuration进行配置

然后依次按照我图中点击即可。

然后依次点击选择自己的Artifacts进行配置。

首先第一步检查配置一下自己本地的Tomcat路径,没问题之后,然后选择我们项目的访问路径,最后点击apply。

最后我们启动项目,如果能访问到默认的JSP页面,说明我们项目环境搭建成功了。

欧克,我们环境搭建篇大功告成!!!

4.数据库准备

4.1 SQL建表语句

大家可通过自行创建SQL表

DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `username` varchar(50) NOT NULL DEFAULT 'default',
  `password` varchar(50) NOT NULL DEFAULT '123456',
  `phone`  varchar(50) NOT NULL ,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1;

4.2 插入数据

INSERT INTO `user` VALUES (1, 'jack', '19978786751', '123456');
INSERT INTO `user` VALUES (2, 'tony', '19975067512', '123123');
INSERT INTO `user` VALUES (3, 'lisa', '19971286751', '123123');

5.编写后端代码

5.1 代码及项目结构总览

5.2 编写实体类

package org.javatop.case01.domain;

/**
 * @author : Leo
 * @version 1.0
 * @date 2023-11-28 20:57
 * @description :
 */
public class User {
    private int id;

    private String username;

    private String password;


    private String phone;


    public User(int id, String username, String password,  String phone) {
        this.id = id;
        this.username = username;
        this.password = password;
        this.phone = phone;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public User() {
    }


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


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

5.3 编写Dao接口

package org.javatop.case01.dao;

import org.javatop.case01.domain.User;

/**
 * @author : Leo
 * @version 1.0
 * @date 2023-11-28 20:59
 * @description :
 */
public interface UserDao {

    // 登录
    User login(String username, String password);

    // 注册
    Boolean register(User user);
}

5.4 编写Dao实现类

package org.javatop.case01.dao.impl;


import org.javatop.case01.dao.UserDao;
import org.javatop.case01.domain.User;
import org.javatop.case01.utils.JdbcUtil;

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

/**
 * @author : Leo
 * @version 1.0
 * @date 2023-11-28 21:01
 * @description :
 */
public class UserDaoImpl  implements UserDao {
    @Override
    public User login(String username, String password) {
        User user = null;
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;

        try {
            connection = JdbcUtil.getConnection();
            String sql = "select * from user where username = ? and password= ?";
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1, username);
            preparedStatement.setString(2, password);
            resultSet = preparedStatement.executeQuery();
            if(resultSet.next()){
                user = new User();
                user.setId(resultSet.getInt("id"));
                user.setUsername(resultSet.getString("username"));
                user.setPassword(resultSet.getString("password"));
                user.setPhone(resultSet.getString("phone"));
                System.out.println("登录成功" + user.toString());
            } else {
                System.out.println("用户名或者密码错误");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JdbcUtil.release(resultSet, preparedStatement, connection);
        }
        return user;
    }

    @Override
    public Boolean register(User user) {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        int result = 0;

        try {
            connection = JdbcUtil.getConnection();
            String sql = "insert into user(username, password) values (?, ?);";
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1, user.getUsername());
            preparedStatement.setString(2, user.getPassword());
            result = preparedStatement.executeUpdate();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JdbcUtil.release(resultSet, preparedStatement, connection);
        }
        // 三目表达式,result等1则人会true,否则返回false
        return result == 1 ? true:false;
    }
}

5.5 实现Servlet

1.LoginServlet
package org.javatop.case01.controller;

import org.javatop.case01.dao.UserDao;
import org.javatop.case01.dao.impl.UserDaoImpl;
import org.javatop.case01.domain.User;

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;

/**
 * @author : Leo
 * @version 1.0
 * @date 2023-12-02 14:34
 * @description :
 */
@WebServlet(name = "/login")
public class LoginServlet extends HttpServlet {

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


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

        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        // 获取前端页面传过来的值
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        // 执行查询数据库逻辑
        UserDao userDao = new UserDaoImpl();
        User user = userDao.login(username, password);

        // 如果根据用户名和密码能查得到值
        if (user != null) {
            request.setAttribute("user", user);
            request.getRequestDispatcher("/su***ess.jsp").forward(request, response);
        } else {    // 用户名或者密码错误执行以下代码
            request.setAttribute("message", "用户名或者密码错误");
            request.getRequestDispatcher("/defeat.jsp").forward(request, response);
        }
    }
}
2.RegisterServlet
package org.javatop.case01.controller;

import org.javatop.case01.dao.UserDao;
import org.javatop.case01.dao.impl.UserDaoImpl;
import org.javatop.case01.domain.User;

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;

/**
 * @author : Leo
 * @version 1.0
 * @date 2023-12-02 16:28
 * @description : 注册接口
 */
@WebServlet(name = "/register")
public class RegisterServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPut(req, resp);
    }

    @Override
    protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");

        String username = req.getParameter("username");
        String password = req.getParameter("password");

        User user = new User();
        user.setUsername(username);
        user.setPassword(password);

        UserDao userDao = new UserDaoImpl();
        if (userDao.register(user)) {
            System.out.println("注册成功");
            // 注册成功,跳转登录页面
            req.getRequestDispatcher("register-su***ess.jsp").forward(req,resp);
        } else {
            System.out.println("注册失败");
            req.setAttribute("message", "注册失败");
            req.getRequestDispatcher("register.jsp").forward(req,resp);
        }

    }
}

5.6 编写数据库连接工具类

package org.javatop.case01.utils;

import java.sql.*;

/**
 * @author : Leo
 * @version 1.0
 * @date 2023-11-28 20:59
 * @description : 数据库连接工具类
 */
public class JdbcUtil {

    /**
     * 1、获取Connection
     * @return Connection
     * @throws Exception
     */
    public static Connection getConnection() throws Exception {

        Class.forName("***.mysql.cj.jdbc.Driver");
        return DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root", "root");

    }

    /**
     * 2、释放资源
     * @param resultSet resultSet
     * @param statement statement
     * @param connection connection
     */
    public static void release(ResultSet resultSet, Statement statement, Connection connection) {
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

6.编写前端代码

这里为了演示效果我实现了两个简单的登录注册页面

6.1 登录页面

<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2023/11/28
  Time: 20:52
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html>
<head>
    <title>Login Page</title>
    <link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="form-container">
    <h2>登录</h2>
    <form action="/login" method="post">
        <input type="text" placeholder="Username" name="username" required>
        <input type="password" placeholder="Password" name="password" required>
        <button type="submit">Login</button>
        <a href="register.jsp">去注册</a>
    </form>
</div>
</body>
</html>

6.2 注册页面

<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2023/11/28
  Time: 20:52
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html>
<head>
    <title>Login Page</title>
    <link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="form-container">
    <h2>注册</h2>
    <form action="/register" method="post">
        <input type="text" placeholder="Username" name="username" required>
        <input type="password" placeholder="Password" name="password" required>
        <button type="submit">注册</button>
    </form>
</div>
</body>
</html>

6.3 登录错误页面

<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2023/11/28
  Time: 21:10
  To change this template use File | Settings | File Templates.
--%>
<%--<%@ page contentType="text/html;charset=UTF-8" language="java"%>--%>
<%@ page contentType="text/html; charset=gb2312" language="java" %>
<html lang="en">
<head>
    <title>登录失败</title>
</head>
<body>
<h1>登录失败!</h1>
<font color="red">
    <%
        if(request.getAttribute("message")!= null){
            response.setContentType("text/html;charset=UTF-8");
            out.print(request.getAttribute("message"));
        }
    %>
</font>
<br>
<a href="login.jsp">重新登录</a>
</body>
</html>

6.4 登录成功页面

<%@ page import="org.javatop.case01.domain.User" %><%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2023/11/28
  Time: 21:10
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=utf-8" language="java" %>
<html lang="en">
<head>
    <title>登录成功</title>
</head>
<body>
<h1>登录成功!</h1>
<br>
<font color="red">
    <%
        User user = (User)request.getAttribute("user");
        String username = user.getUsername();
    %>
    欢迎您:
    <%
        out.print(username);
    %>
</font>

</body>
</html>

6.5 注册成功页面

<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2023/11/28
  Time: 21:10
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html lang="en">
<head>************************c
    <title>注册成功</title>
</head>
<body>
<h1>注册成功!</h1>
<br>
<a href="login.jsp">跳转登录</a>
<a href="register.jsp">继续注册</a>
</body>

7.总结

本篇教程内容比较长,适合初学者学习,但是也需要有一点基础,比如环境的配置,但如果你稍微有点基础,操作一下这篇文章是非常不错的,特别是代码。

8.最后总结

以上便是本文的全部内容,本人才疏学浅,文章有什么错误的地方,欢迎大佬们批评指正!我是Leo,一个在互联网行业的小白,立志成为更好的自己。

如果你想了解更多关于Leo,可以关注公众号-程序员Leo,后面文章会首先同步至公众号。

转载请说明出处内容投诉
CSS教程_站长资源网 » 使用JSP+Servlet+MySQL实现登录注册功能

发表评论

欢迎 访客 发表评论

一个令你着迷的主题!

查看演示 官网购买