1. Session基本使用
将数据(cookie)保存在客户端不安全,因为客户端在不停的进行着网络传输,所以把数据存储在服务端。
存储的对象就是session,例如AServlet往session中存数据,BServlet往session中读数据。
创建
demo1
用来存储数据,demo2
用来读数据
@WebServlet("/demo1")
public class SessionDemo1 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//存储到Session中
//1. 获取Session对象
HttpSession session = request.getSession();
System.out.println(session);
//2. 存储数据
session.setAttribute("username","zs");
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}
@WebServlet("/demo2")
public class SessionDemo2 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获取数据,从session中
//1. 获取Session对象
HttpSession session = request.getSession();
System.out.println(session);
//2. 获取数据
Object username = session.getAttribute("username");
System.out.println(username);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}
2. Session原理及细节
怎么保证两次获取的session是一个
并且不同的会话都要获取session,是否是同一个session(并不是)
所以怎么保证同一会话获取的session是同一个,引出相关原理
当
demo1
来获取session时,这个session是有一个唯一标识的,例如:id=10
,这是Tomcat要给客户端浏览器做出响应,如果使用session,Tomcat会自动把id
当做cookie,发送个客户端浏览器;
响应头是set-cookie:JSESSION=10
,从而浏览器解析并存入内存中;然后该会话下一次请求时,会携带该cookie信息访问demo2,设置请求头cookie-JSESSION=10
,demo2就会内存中找是否有id=10
的session
所以这就是为什么其他会话无法访问另一个会话的session
2. Session使用细节
2.1 Session 钝化、活化
注意:再次启动时,session文件是会被删除的,等服务器关闭之后,又会访问硬盘中,对象序列化和反序列化(Tomcat内部自动实现)
当关闭浏览器,再次访问时,id值会变化,此时已经时两次会话了