Session基本用法
request.getSession():无参方法,有老的session时,用老的session。没有老的session,创建新的session。一般在存储数据的时候使用。
request.getSession(Boolean):参数为true时,等同于无参的方法。为false时,有老的session用老的session,没有则返回null。
Session的工作原理
1.写入Session列表
当用户第一次提交一个请求的时候,服务器中执行到getSession()方法后,主动生成一个Map.entry对象。key是某种算法新生成JSessionID,value则是新创建session的引用。
2.服务器生成并发送cookie
服务器会把JSessionID生成为一个cookie,名为JSessionID,值为JSessionID的的值,并将cookie发送到服务端。服务器获取数据时,根据发送过来的cookie产找对应的session,找到对应的值。
3.客户端接受并发送cookie
服务器相应到客户端时,客户端会接受session和cookie,将cookie保存到缓存中。页面没关闭的时,在发送请求时,会直接将缓存的中的cookie发送到服务器,服务器直接根据cookie查找session,不需要创建。
Session失效
1.session.invalidate():可以使session失效。解绑所有绑定在session中的对象。此方法不会让session为null。
2.设置session的失效时长为10分钟。
web.xml
<session-config>
<session-timeout>10</session-timout>
</session-config>
Cookie禁用后重定向session的会话跟踪
cookie禁用,不能使用cookie中的JSessionID来查找session。
只需要使用uri = response.encodeRedirectURL(uri);
重写uri地址即可。
index.html
<body>
<form action="${pageContext.request.contextPath}/someServlet">
<input type="text" name="user"/>
</form>
</body>
保存index.html页面数据的Servlet
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String username = request.getParameter("user");
HttpSession session = request.getSession();
session.setAttribute("username", username);
response.getWriter().write(username);
String uri = request.getContextPath()+"/otherServlet";
//重写uri地址,在地址后面添加JSessionID
uri = response.encodeRedirectURL(uri);
response.sendRedirect(uri);
}
重定向获取数据页面。
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession(false);
String username = (String) session.getAttribute("username");
response.getWriter().write(username);
}
非重定向禁用cookie时,追踪Session会话
原理同上,只是重写uri地址的方法是uri = response.encodeURL(uri);
即可。