当客户端关闭后,服务器不关闭,两次获取Session是否为同一个

    默认情况下,不是

  如果相同,则可以创建Cookie,键为JESSIONID,设置最大存活时间,让cookie持久化保存

  Cookie cookie = new Cookie("JSESSIONID",session.getId());

   cookie.setMaxAge(60*60);

   response.addCookie(cookie);

 

 

@WebServlet("/SessionDemo3")
public class SessionDemo3 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        HttpSession session = request.getSession();
        System.out.println(session);

        Cookie cookie = new Cookie("JSESSIONID",session.getId());
        cookie.setMaxAge(60*60);
        response.addCookie(cookie);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

会话技术_session_细节2

 

客户端不关闭,服务器关闭后,两次获取的Session是同一个吗?

  不是同一个,但是要确保数据不丢失

    Session的钝化

        在服务器正常关闭之前,将session对象系列化到硬盘上

    Session的活化

        在服务器启动后,将session文件转化为内存中的session对象即可。

@WebServlet("/SessionDemo3")
public class SessionDemo3 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        HttpSession session = request.getSession();
        System.out.println(session);

        Cookie cookie = new Cookie("JSESSIONID",session.getId());
        cookie.setMaxAge(60*60);
        response.addCookie(cookie);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}

 

posted on 2022-08-15 10:35  淤泥不染  阅读(15)  评论(0编辑  收藏  举报