You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将MySQL与Servlet对接实现登录页面的数据库用户验证

如何将Login Servlet从硬编码验证改为MySQL数据库验证?

没问题,我来一步步教你把硬编码的用户验证逻辑改成从MySQL数据库读取信息来验证:

第一步:准备MySQL数据库和用户表

首先你得在MySQL里创建一个存储用户信息的数据库和表,比如我们创建一个user_db数据库,里面建一张users表来存用户名和密码(注意:实际项目里一定要加密密码,这里先做基础验证演示)。执行下面的SQL语句:

CREATE DATABASE IF NOT EXISTS user_db;
USE user_db;

CREATE TABLE IF NOT EXISTS users (
    username VARCHAR(50) PRIMARY KEY,
    password VARCHAR(50) NOT NULL
);

-- 插入你需要的测试用户,比如你提到的konsta/4321和原有的gogikole/1234
INSERT INTO users (username, password) VALUES ('gogikole', '1234'), ('konsta', '4321');

第二步:修改Login Servlet代码

接下来要替换原来的硬编码判断逻辑,添加JDBC连接数据库的代码。需要注意:

  • 导入JDBC相关的类
  • 配置你的MySQL连接参数(根据自己的数据库设置调整)
  • 使用try-with-resources自动关闭数据库资源,避免连接泄漏
  • 查询数据库验证用户名和密码

修改后的完整LoginServlet代码如下:

package servlets;

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;

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    // 数据库连接配置,替换成你自己的MySQL信息
    private static final String DB_URL = "jdbc:mysql://localhost:3306/user_db?useSSL=false&serverTimezone=UTC";
    private static final String DB_USER = "root"; // 你的MySQL用户名
    private static final String DB_PASSWORD = "your_mysql_password"; // 你的MySQL密码

    public LoginServlet() {
        super();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // GET请求直接跳转到登录页
        response.sendRedirect("login.jsp");
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        
        // 先做简单的非空校验
        if (username == null || username.isEmpty() || password == null || password.isEmpty()) {
            request.setAttribute("errorMsg", "用户名或密码不能为空");
            request.getRequestDispatcher("login.jsp").forward(request, response);
            return;
        }

        boolean isAuthenticated = false;
        
        // 使用try-with-resources自动关闭连接、语句、结果集,不用手动close
        try (Connection conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
             PreparedStatement stmt = conn.prepareStatement("SELECT password FROM users WHERE username = ?")) {
            
            stmt.setString(1, username);
            ResultSet rs = stmt.executeQuery();
            
            if (rs.next()) {
                String storedPassword = rs.getString("password");
                // 这里直接明文比较,实际项目一定要用BCrypt等加密算法!
                if (password.equals(storedPassword)) {
                    isAuthenticated = true;
                }
            }
            
        } catch (SQLException e) {
            e.printStackTrace();
            request.setAttribute("errorMsg", "数据库连接异常,请稍后重试");
            request.getRequestDispatcher("login.jsp").forward(request, response);
            return;
        }

        if (isAuthenticated) {
            response.sendRedirect("mainMenu.jsp");
        } else {
            request.setAttribute("errorMsg", "用户名或密码错误");
            request.getRequestDispatcher("login.jsp").forward(request, response);
        }
    }
}

第三步:优化login.jsp显示错误提示

为了让用户知道登录失败的原因,我们可以给login.jsp添加错误信息的显示逻辑,同时保留用户输入的用户名,提升体验:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Login page</title>
<style>
.error { color: red; text-align: center; margin-bottom: 10px; }
</style>
</head>
<body>
    <%-- 显示错误提示信息 --%>
    <% String errorMsg = (String) request.getAttribute("errorMsg"); %>
    <% if (errorMsg != null && !errorMsg.isEmpty()) { %>
        <div class="error"><%= errorMsg %></div>
    <% } %>

    <form method="post" action="LoginServlet">
        <table align="center">
            <tr>
                <td>User name</td>
                <td><input type="text" name="username" value="<%= request.getParameter("username") != null ? request.getParameter("username") : "" %>"></td>
            </tr>
            <tr>
                <td>Password</td>
                <td><input type="password" name="password"></td>
            </tr>
            <tr>
                <td></td>
                <td><input type="submit" value="Login"></td>
            </tr>
        </table>
    </form>
</body>
</html>

重要注意事项

  • 密码安全:上面的代码是明文存储和比较密码,这在生产环境中绝对不安全!建议使用BCrypt、Argon2等加密算法,存储时加密密码,验证时加密用户输入的密码再和数据库中的密文比较。
  • 数据库配置:记得把代码里的DB_URL、DB_USER、DB_PASSWORD替换成你自己的MySQL实际配置(比如端口、用户名、密码)。
  • 异常处理:示例中只是简单打印异常,实际项目建议使用日志框架记录异常,不要直接打印到控制台。

内容的提问来源于stack exchange,提问作者Neo Cortex

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 04:28:12