• 博客园logo
  • 会员
  • 周边
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

gsq123

  • 博客园
  • 联系
  • 订阅
  • 管理

公告

View Post

登录验证

Java Web 登录验证系统

一、功能概述

简单的网站登录系统:

  • 预置两组合法账号密码:123/123 和 qwe/qwe
  • 首次登录成功后,将凭据保存到 Cookie(有效期 3 天)
  • 3 天内再次访问,自动读取 Cookie 完成登录
  • 超过 3 天需重新输入账号密码
  • 验证失败提示错误信息

二、项目结构

login-app/
├── index.jsp # 首页(登录表单 + 欢迎页)
├── WEB-INF/
│ ├── web.xml # 部署描述符
│ └── classes/
│ └── servlet/
│ └── LoginServlet.java # 登录处理逻辑

text


三、核心代码

1. 登录验证逻辑 (LoginServlet.java)

public class LoginServlet extends HttpServlet {

    // 预定义的合法账号密码
    private static final Map<String, String> VALID_USERS = new HashMap<>();
    
    static {
        VALID_USERS.put("123", "123");
        VALID_USERS.put("qwe", "qwe");
    }

    private static final long THREE_DAYS_MILLIS = 3L * 24 * 60 * 60 * 1000;

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        if (isValidCredentials(username, password)) {
            // 登录成功:设置 Session
            request.getSession().setAttribute("loggedInUser", username);

            // 保存凭据到 Cookie(3天有效期)
            long loginTime = System.currentTimeMillis();
            Cookie usernameCookie = new Cookie("savedUsername", URLEncoder.encode(username, "UTF-8"));
            Cookie passwordCookie = new Cookie("savedPassword", Base64.getEncoder().encodeToString(password.getBytes()));
            Cookie timeCookie = new Cookie("loginTime", String.valueOf(loginTime));
            
            for (Cookie c : new Cookie[]{usernameCookie, passwordCookie, timeCookie}) {
                c.setMaxAge((int)(THREE_DAYS_MILLIS / 1000));
                c.setPath("/");
                c.setHttpOnly(true);
                response.addCookie(c);
            }
            response.sendRedirect("index.jsp");
        } else {
            // 登录失败
            request.getSession().setAttribute("errorMessage", "身份验证失败,必须重新输入");
            response.sendRedirect("index.jsp");
        }
    }

    public static boolean isValidCredentials(String username, String password) {
        if (username == null || password == null) return false;
        String correctPassword = VALID_USERS.get(username.trim());
        return correctPassword != null && correctPassword.equals(password);
    }
}

设计点:

用户名和密码都存入 Cookie,密码用 Base64 编码

登录时间戳用于判断是否超过 3 天

  1. 首页自动登录逻辑 (index.jsp)
<%
    // 检查 Session 是否已登录
    boolean isLoggedIn = (session.getAttribute("loggedInUser") != null);

    // 如果未登录,尝试从 Cookie 中读取凭据自动登录
    if (!isLoggedIn) {
        String savedUsername = null, savedPassword = null, savedLoginTime = null;
        
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if ("savedUsername".equals(cookie.getName())) savedUsername = cookie.getValue();
                if ("savedPassword".equals(cookie.getName())) savedPassword = cookie.getValue();
                if ("loginTime".equals(cookie.getName())) savedLoginTime = cookie.getValue();
            }
        }

        if (savedUsername != null && savedPassword != null && savedLoginTime != null) {
            long loginTime = Long.parseLong(savedLoginTime);
            if ((System.currentTimeMillis() - loginTime) <= THREE_DAYS_MILLIS) {
                // 解码凭据并在服务器端验证
                String username = URLDecoder.decode(savedUsername, "UTF-8");
                String password = new String(Base64.getDecoder().decode(savedPassword));
                
                if (LoginServlet.isValidCredentials(username, password)) {
                    session.setAttribute("loggedInUser", username);  // 自动登录
                    isLoggedIn = true;
                }
            }
        }
    }
%>

自动登录流程:

先检查 Session,有则直接展示欢迎页

没有则读取 Cookie 中的凭据和时间戳

检查是否在 3 天内,再调用服务器的 isValidCredentials 验证

验证通过自动建立 Session,失败则显示登录表单

四、运行截图

  1. 输入界面
    image
  2. 登录成功
    image
  3. 登录失败
    image
  4. 欢迎回来
    image
    五、验证流程总结
    用户访问 → 检查Session
    ├─ 有 → 显示欢迎页
    └─ 无 → 检查Cookie
    ├─ 无Cookie → 显示登录表单
    ├─ 有Cookie但超3天 → 清除Cookie → 显示登录表单
    └─ 有Cookie且3天内 → 服务器验证凭据
    ├─ 合法 → 自动登录 → 显示欢迎页
    └─ 非法 → 提示验证失败

posted on 2026-05-17 13:27  YyB123  阅读(16)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2026
浙公网安备 33010602011771号 浙ICP备2021040463号-3