Session的工作原理以及实操


原理

Session 依赖于 Cookie

当客户端首次访问服务器时,服务器会为其创建一个 session 对象,该对象具有一个唯一标识 SESSIONID。并且在响应阶段,服务器会创建一个 cookie,并将 SESSIONID 存入其中。

客户端通过响应的 cookie 而持有 SESSIONID,所以当它再次访问服务器时,会通过 cookie 携带这个 SESSIONID。服务器获取到 SESSIONID 后,就可以找到与之对应的 session 对象,进而从这个 session 中获取该客户端的状态。

示例

存储用户信息

  1. 用户端发起 POST 请求,服务端进行一定的逻辑处理后把用户信息存储在 Session。
protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String username = request.getParameter("username");
        String email = request.getParameter("email");

        // 创建或获取会话对象
        HttpSession session = request.getSession();
        
        // 将用户信息存储在会话中
        session.setAttribute("username", username);
        session.setAttribute("email", email);

        // 重定向到用户信息展示页面
        response.sendRedirect(request.getContextPath() + "/userInfo.jsp");
    }
  1. 客户端请求时携带带有 sessionID 的 Cookie,判断是否存在该 sessionID,如果存在则可以取出数据。
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取请求中的所有Cookie
        Cookie[] cookies = request.getCookies();

        if (cookies != null) {
            // 遍历Cookie找到名为 "JSESSIONID" 的Cookie
            for (Cookie cookie : cookies) {
                if ("JSESSIONID".equals(cookie.getName())) {
                    // 获取Session ID
                    String sessionID = cookie.getValue();

                    // 获取或创建与该Session ID关联的会话
                    HttpSession session = request.getSession(false);

                    if (session != null && session.getId().equals(sessionID)) {
                        // 会话存在且Session ID有效
                        // 可以在此处验证用户身份或执行其他操作
                        // 例如:String username = (String) session.getAttribute("username");

                        // 返回验证成功的响应
                        response.getWriter().println("Session is valid.");
                        return;
                    }
                }
            }
        }

        // 没有有效的会话或Session ID,需要重定向到登录页面或其他处理方式
        response.getWriter().println("Session is invalid.");

双链

table file.inlinks as 被引用
where file = this.file
limit 1

文章作者: KTpro
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 KTpro !
评论
  目录