使用Java的session判断用户是否登录

1. 流程概述

下面是实现Java使用session判断用户是否登录的流程:

gantt
    dateFormat  YYYY-MM-DD
    title Java使用session判断用户是否登录流程

    section 创建登录页面
    创建登录页面           :active, 2022-11-01, 1d

    section 处理登录请求
    接收登录请求           :active, 2022-11-02, 1d
    验证用户名和密码       :active, 2022-11-03, 1d

    section 设置Session
    创建Session对象        :active, 2022-11-04, 1d
    将用户信息存储到Session :active, 2022-11-04, 1d
    将Session保存到Cookie   :active, 2022-11-04, 1d

    section 判断用户是否登录
    检查Session是否存在    :active, 2022-11-05, 1d
    检查Session中的用户信息 :active, 2022-11-05, 1d
    判断用户是否登录        :active, 2022-11-05, 1d

    section 登出功能
    注销Session            :active, 2022-11-06, 1d

2. 步骤和代码

2.1. 创建登录页面

首先,我们需要创建一个登录页面,让用户输入用户名和密码。这个页面可以使用HTML和CSS来实现。以下是一个简单的登录页面的示例代码:

<!DOCTYPE html>
<html>
<head>
    <title>Login Page</title>
</head>
<body>
    <h2>Login Form</h2>
    <form action="login" method="post">
        <div>
            <label for="username">Username:</label>
            <input type="text" id="username" name="username">
        </div>
        <div>
            <label for="password">Password:</label>
            <input type="password" id="password" name="password">
        </div>
        <div>
            <input type="submit" value="Login">
        </div>
    </form>
</body>
</html>

2.2. 处理登录请求

当用户点击登录按钮时,我们需要处理登录请求。这可以通过创建一个Servlet来实现。以下是一个处理登录请求的Servlet的示例代码:

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        // 验证用户名和密码
        if (username.equals("admin") && password.equals("password")) {
            // 登录成功
            // 创建Session对象
            HttpSession session = request.getSession(true);
            // 将用户信息存储到Session
            session.setAttribute("username", username);
            // 将Session保存到Cookie
            Cookie cookie = new Cookie("sessionId", session.getId());
            cookie.setMaxAge(24 * 60 * 60); // 设置Cookie的有效期为1天
            response.addCookie(cookie);

            response.sendRedirect("home.jsp"); // 重定向到首页
        } else {
            // 登录失败
            response.sendRedirect("login.jsp?error=1"); // 重定向到登录页面,并传递错误信息
        }
    }
}

2.3. 判断用户是否登录

在其他需要判断用户是否登录的页面或功能中,我们需要检查Session是否存在,并检查Session中的用户信息。以下是一个判断用户是否登录的示例代码:

@WebServlet("/profile")
public class ProfileServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession(false);

        // 检查Session是否存在
        if (session != null) {
            // 检查Session中的用户信息
            String username = (String) session.getAttribute("username");
            if (username != null) {
                // 用户已登录
                // 显示用户资料页面
                response.getWriter().println("Welcome, " + username);
                return;
            }
        }

        // 用户未登录
        response.sendRedirect("login.jsp");
    }
}

2.4. 登出功能

最后,我们还需要提供一个登出功能,让用户可以安全地退出登录。以下是一个提供登出功能的Servlet的示例代码:

@WebServlet("/logout")
public class LogoutServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession(false);
        
        // 注销Session
        if (session != null) {
            session.invalidate();