标签:cookie nbsp row except apache max exce class col
1 package com.haifei.session; 2 3 import javax.servlet.ServletException; 4 import javax.servlet.annotation.WebServlet; 5 import javax.servlet.http.*; 6 import java.io.IOException; 7 8 /** 9 * session细节 10 * 11 * 1. 当客户端关闭后,服务器不关闭,两次获取session是否为同一个? 12 * * 默认情况下。不是。 13 * * 如果需要相同,则可以创建Cookie,键为JSESSIONID,设置最大存活时间,让cookie持久化保存。 14 * 15 */ 16 @WebServlet("/SessionDemo3") 17 public class SessionDemo3 extends HttpServlet { 18 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 19 /*HttpSession session = request.getSession(); 20 System.out.println(session);*/ 21 /* 22 浏览器首次访问http://localhost:8080/day16/SessionDemo3 23 org.apache.catalina.session.StandardSessionFacade@cab793b 24 25 浏览器重启后访问http://localhost:8080/day16/SessionDemo3 26 org.apache.catalina.session.StandardSessionFacade@4fc2488e 27 */ 28 29 HttpSession session = request.getSession(); 30 System.out.println(session); 31 //期望客户端(浏览器)重启后,session也能相同 32 Cookie cookie = new Cookie("JSESSIONID", session.getId()); 33 cookie.setMaxAge(60 * 60); //设置cookie存活时间为1H 34 response.addCookie(cookie); 35 /* 36 浏览器首次访问http://localhost:8080/day16/SessionDemo3 37 org.apache.catalina.session.StandardSessionFacade@cab793b 38 39 浏览器重启后访问http://localhost:8080/day16/SessionDemo3 40 org.apache.catalina.session.StandardSessionFacade@cab793b 41 */ 42 } 43 44 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 45 this.doPost(request, response); 46 } 47 }
1 package com.haifei.session; 2 3 import javax.servlet.ServletException; 4 import javax.servlet.annotation.WebServlet; 5 import javax.servlet.http.*; 6 import java.io.IOException; 7 8 /** 9 * session细节 10 * 11 * 2. 客户端不关闭,服务器关闭后,两次获取的session是同一个吗? 12 * * 不是同一个。 13 * * 但是要确保数据不丢失,tomcat会自动完成以下工作: 14 * * session的钝化 15 * * 在服务器正常关闭之前,将session对象序列化到硬盘上 16 * * session的活化 17 * * 在服务器启动后,将session文件转化为内存中的session对象(反序列化) 18 * * 即就算服务器重启前后的session对象不是同一个,但后面的对象能够自动获取到前面对象中的数据 19 * 20 */ 21 @WebServlet("/SessionDemo4") 22 public class SessionDemo4 extends HttpServlet { 23 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 24 HttpSession session = request.getSession(); 25 System.out.println(session); 26 /* 27 服务器重启前访问http://localhost:8080/day16/SessionDemo4 28 org.apache.catalina.session.StandardSessionFacade@62eeba2f 29 30 服务器重启后访问http://localhost:8080/day16/SessionDemo4 31 org.apache.catalina.session.StandardSessionFacade@791295a 32 */ 33 } 34 35 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 36 this.doPost(request, response); 37 } 38 }
JavaWeb16.6【Cookie&Session:Session细节、特点】
标签:cookie nbsp row except apache max exce class col
原文地址:https://www.cnblogs.com/yppah/p/14966069.html