Java简易登录系统采用Servlet+JDBC+Session实现,密码用BCrypt加盐哈希存储与校验,PreparedStatement防SQL注入,Session管理登录态并配置超时,退出时调用invalidate()彻底销毁会话。
Java实现简单用户登录系统,核心在于验证用户输入的账号密码是否与存储的信息一致,并合理管理会话状态。不依赖Spring Security等框架时,可用Servlet + JDBC + Session完成基础认证流程,重点是安全处理密码、防止SQL注入、控制会话生命周期。
不要明文保存密码。使用BCrypt或SHA-256加盐哈希(推荐BCrypt,它内置随机盐且抗暴力破解)。
BCrypt.hashpw(password, BCrypt.gensalt())生成哈希值再存入数据库BCrypt.checkpw(inp
utPassword, storedHash)比对,不直接比较字符串在LoginServlet中接收表单参数,查询数据库并校验:
SELECT id, username, password_hash FROM users WHERE username = ?
request.getSession().setAttribute("userId", userId)标记登录态受保护资源(如主页、个人中心)需检查Session中是否存在有效用户ID:
Integer userId = (Integer) request.getSession().getAttribute("userId")
response.sendRedirect(request.getContextPath() + "/login.jsp")
doFilter()中统一判断并放行/跳转退出操作不是简单删除Session属性,而是使整个Session失效:
LogoutServlet中调用request.getSession().invalidate()
getSession()会新建Session,确保旧ID彻底作废不复杂但容易忽略细节:密码校验必须用专用函数比对哈希,Session超时时间可在web.xml中配置,单位为分钟。