基于Servlet+JSP+JDBC的登录注册案例

这是一个适合学完Servlet+JSP+JDBC的练手例子,动手之前可以先回顾一下本文需要用到的知识 ~>
Servlet回顾传送门
JSP回顾: 传送门

JDBC使用步骤回顾 ~>
1、加载驱动
2、获取连接对象
3、通过连接对象获取sql执行对象
4、编写sql语句
5、使用sql执行对象执行sql语句(为语句中的变量赋值)
6、sql执行对象调用执行方法
如果是查询调用executeQuery();
如果是增删改调用executeUpdate()。
7、释放资源

Start ~>

1、创建一个javaweb工程,导入依赖

导入mysql连接:

<dependency>
	<groupId>mysql</groupId>
	<artifactId>mysql-connector-java</artifactId>
	<version>8.0.27</version>
</dependency>

2、创建数据库user表

在数据库中创建名为test的数据库,执行以下sql创建user表:

CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
`password` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8;

3、创建实体类

public class User {

    private Integer id;
    private String username;
    private String password;

    public User() {
    }

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

    public Integer getId() {
        return id;
    }

    public void setId(Integer 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;
    }
}

3、创建jdbc工具类

将JDBC中的一些步骤编写成工具类,减少重复代码。

public class JDBCUtil {

    static Connection connection = null;
    static PreparedStatement preparedStatement = null;
    static ResultSet resultSet = null;
	//加载驱动
    static {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
	//获取数据库连接
    public static Connection getConnection(){
        //数据库连接路径
        String url = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8";
        //数据库账号
        String username = "root";
        //数据库密码
        String password = "root";
        try {
            connection = DriverManager.getConnection(url,username,password);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return connection;
    }
	//释放资源
    public static void release(Connection connection,PreparedStatement preparedStatement){
        if (connection != null){
            try {
                connection.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (preparedStatement != null){
            try {
                preparedStatement.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
    public static void release(Connection connection,PreparedStatement preparedStatement,ResultSet resultSet){
        release(connection,preparedStatement);
        if (resultSet != null){
            try {
                resultSet.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        Connection connection = JDBCUtil.getConnection();
        System.out.println(connection);
    }

}

4、创建repository,编写登录方法(查询),注册方法(添加)

public class UserRepository {

    public void register(String username,String password){
        Connection connection = JDBCUtil.getConnection();
        PreparedStatement preparedStatement = null;
        String sql = "insert into user(username,password) values(?,?)";
        try {
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1,username);
            preparedStatement.setString(2,password);
            preparedStatement.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            JDBCUtil.release(connection,preparedStatement);
        }
    }

    public User login(String username,String password){
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        User user = null;
        String sql = "select * from user where username = ? and password = ?";
        try {
            connection = JDBCUtil.getConnection();
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1,username);
            preparedStatement.setString(2,password);
            resultSet = preparedStatement.executeQuery();
            while (resultSet.next()){
                int id = resultSet.getInt(1);
                String name = resultSet.getString(2);
                String pwd = resultSet.getString(3);
                user = new User(id,name,pwd);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            JDBCUtil.release(connection,preparedStatement,resultSet);
        }
        return user;
    }

}

5、创建LoginServlet和RegisterServlet分别调用登录和注册方法

访问Servlet程序的映射可以在web.xml中配置,也可以使用注解@WebServlet替代,更为方便。

@WebServlet("/login")
public class LoginServlet extends HttpServlet {

    //访问:http://localhost:8080/login进入get方法,跳转到登录页面
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.sendRedirect("index.jsp");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        UserRepository userRepository = new UserRepository();
        User user = userRepository.login(username, password);
        if (user != null){
            req.getRequestDispatcher("homePage.jsp").forward(req,resp);
        }
        req.setAttribute("msg","用户名或密码错误!");
        req.getRequestDispatcher("index.jsp").forward(req,resp);
    }

}
@WebServlet("/register")
public class RegisterServlet extends HttpServlet {

    //访问:http://localhost:8080/register进入get方法,跳转到注册页面
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("register.jsp").forward(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        UserRepository userRepository = new UserRepository();
        userRepository.register(username,password);
        req.getRequestDispatcher("index.jsp").forward(req,resp);
    }

}

6、编写登录和注册页面 登录页面

登录页面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>登录</title>
</head>
<body>
<h1>LOGIN</h1>
<form action="/login" method="post">
    <div>
        <input type="text" name="username" placeholder="UserName">
    </div>
    <div>
        <input type="password" name="password" placeholder="UserPassword">
    </div>
    <input type="submit" value="Sign in">
    <a href="/register">Register</a>
</form>
<%
    String msg = (String)request.getAttribute("msg");
%>
<%
    if (msg != null){
        response.getWriter().write(msg);
    }
%>

</body>
</html>

注册页面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>注册</title>
</head>
<body>

<h1>register</h1>
<form action="/register" method="post">
    <div>
        <input type="text" name="username" placeholder="Enter UserName">
    </div>
    <div>
        <input type="password" name="password" placeholder="Enter UserPassword">
    </div>
    <input type="submit" value="Register">
</form>

</body>
</html>

主页

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>主页</title>
</head>
<body>
<h1>Welcome!!!</h1>
</body>
</html>

运行截图:

在这里插入图片描述

7、添加过滤器

在注册的时候如果输入中文,在数据库中可以看到是乱码的,这时候可以使用过滤器来解决编码问题。
创建一个类实现Filter接口,在doFilter方法中设置编码为UTF-8:
注解@WebFilter(“/*”)表示过滤所有请求,如果你只想过滤部分请求,那么在斜杆之后加上请求的url即可,例如过滤注册请求:@WebFilter(“/register”)。

@WebFilter("/*")
public class MyFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        servletRequest.setCharacterEncoding("UTF-8");
        filterChain.doFilter(servletRequest,servletResponse);
    }
}

项目结构:
在这里插入图片描述

  • 0
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是一个简单的使用 JDBCServlet 实现用户注册和登录功能的示例代码: 1. 首先,我们需要创建一个数据库表来存储用户信息,例如: CREATE TABLE users ( id INT PRIMARY KEY AUTO_INCREMENT, username VARCHAR(50) NOT NULL UNIQUE, password VARCHAR(50) NOT NULL ); 2. 接下来,我们需要编写一个注册 Servlet,用于处理用户提交的注册表单。以下是一个示例代码: import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/register") public class RegisterServlet extends HttpServlet { private static final long serialVersionUID = 1L; // 数据库连接信息 private static final String URL = "jdbc:mysql://localhost:3306/test"; private static final String USER = "root"; private static final String PASSWORD = "123456"; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 获取用户提交的注册信息 String username = request.getParameter("username"); String password = request.getParameter("password"); // 插入用户信息到数据库 try (Connection conn = DriverManager.getConnection(URL, USER, PASSWORD)) { String sql = "INSERT INTO users (username, password) VALUES (?, ?)"; PreparedStatement stmt = conn.prepareStatement(sql); stmt.setString(1, username); stmt.setString(2, password); stmt.executeUpdate(); // 注册成功后跳转到登录页面 response.sendRedirect("login.html"); } catch (SQLException e) { e.printStackTrace(); } } } 3. 然后,我们需要编写一个登录 Servlet,用于验证用户提交的登录信息。以下是一个示例代码: import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; 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 javax.servlet.http.HttpSession; @WebServlet("/login") public class LoginServlet extends HttpServlet { private static final long serialVersionUID = 1L; // 数据库连接信息 private static final String URL = "jdbc:mysql://localhost:3306/test"; private static final String USER = "root"; private static final String PASSWORD = "123456"; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 获取用户提交的登录信息 String username = request.getParameter("username"); String password = request.getParameter("password"); // 验证用户信息是否正确 try (Connection conn = DriverManager.getConnection(URL, USER, PASSWORD)) { String sql = "SELECT * FROM users WHERE username=? AND password=?"; PreparedStatement stmt = conn.prepareStatement(sql); stmt.setString(1, username); stmt.setString(2, password); ResultSet rs = stmt.executeQuery(); if (rs.next()) { // 登录成功,将用户信息保存到 Session 中 HttpSession session = request.getSession(); session.setAttribute("username", username); response.sendRedirect("welcome.jsp"); } else { // 登录失败,返回错误信息 response.sendRedirect("login.html?error=1"); } } catch (SQLException e) { e.printStackTrace(); } } } 4. 最后,我们需要编写一个欢迎页面,用于显示用户登录成功后的信息。以下是一个示例代码: <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>欢迎</title> </head> <body> <h1>欢迎 <%= session.getAttribute("username") %>!</h1> <a href="logout">退出</a> </body> </html> 以上就是一个简单的使用 JDBCServlet 实现用户注册和登录功能的示例代码。当然,这只是一个示例,实际应用中可能需要更复杂的逻辑和更完善的安全性措施。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值