在開發 Web 應用程式時,用戶登錄驗證是最基礎也是最關鍵的功能之一。許多初學者在使用 JSP 實現登錄界面並調用資料庫進行帳號密碼匹配時,常會遇到各種錯誤。本文將提供一個清晰、可運行的完整案例,幫助你快速掌握核心邏輯。
採用經典的 JSP + Servlet + JDBC + MySQL 架構,前端負責頁面展示與交互,後端處理業務邏輯與資料庫操作。為了提升用戶體驗,建議使用 AJAX 異步提交,避免頁面刷新帶來的閃爍感。
首先在 MySQL 中建立用戶表:
CREATE TABLE users (
id INT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(50) UNIQUE NOT NULL,
password VARCHAR(100) NOT NULL
);
<form id="loginForm">
<input type="text" id="username" placeholder="用戶名" required>
<input type="password" id="password" placeholder="密碼" required>
<button type="button" onclick="doLogin()">登錄</button>
<span id="msg"></span>
</form>
function doLogin() {
var user = $("#username").val();
var pwd = $("#password").val();
$.post("LoginServlet", {username: user, password: pwd}, function(res) {
if (res === "success") {
window.location.href = "welcome.jsp";
} else {
$("#msg").text("用戶名或密碼錯誤");
}
});
}
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
String username = req.getParameter("username");
String password = req.getParameter("password");
try (Connection conn = DBUtil.getConnection();
PreparedStatement ps = conn.prepareStatement("SELECT * FROM users WHERE username=? AND password=?")) {
ps.setString(1, username);
ps.setString(2, password); // 實際項目請使用加密密碼
ResultSet rs = ps.executeQuery();
resp.getWriter().print(rs.next() ? "success" : "fail");
} catch (SQLException e) {
e.printStackTrace();
resp.getWriter().print("error");
}
}
}
引入驗證碼防暴力破解、實現「記住我」功能(Cookie+Token)、採用 JWT 進行無狀態認證、增加登錄日誌審計等。掌握基礎流程後,可根據業務場景逐步增強安全性與體驗。
JSP 登錄系統的核心在於:前端收集數據 → AJAX 異步提交 → Servlet 接收參數 → JDBC 參數化查詢 → 返回結果 → 前端跳轉或提示。只要理清這條鏈路,並注意編碼、防注入、密碼加密三大細節,就能構建出穩健的登錄模塊。