一、Session
我们把这种基于唯一ID识别用户身份的机制称为Session
。每个用户第一次访问服务器后,会自动获得一个Session ID
。如果用户在一段时间内没有访问服务器,那么Session
会自动失效,下次即使带着上次分配的Session ID
访问,服务器也认为这是一个新用户,会分配新的Session ID
。一次Session
会话中往往包含着若干次request
请求。
JavaEE
的Servlet
机制内建了对Session
的支持。当我们需要获取Session
时,可以通过request
请求对象的getSession()
方法。
例如:
@WebServlet("/test_get_cookie_value.do")
public class TestGetCookieServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("获取测试Cookie");
// 获取该客户端浏览器本次请求头(Request Header)中所有Cookie
Cookie[] cookieArray = req.getCookies();
if (cookieArray != null) {
for (Cookie cookie : cookieArray) {
System.out.println(cookie.getName());
System.out.println(cookie.getValue());
System.out.println();
}
}
}
}
请求后服务器得到Cookie,并打印
同一个无论请求多少次,SessionId是不会变的。SessioId是客户端发送第一次请求时,由服务器创建出来,给此次请求的一个标识。到浏览器客户端时,将SessionId以及Cookie对象都存入浏览器的Cookie中
@WebServlet("/test_cookie.do")
public class TestCookieServlet extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Cookie cookie = new Cookie("QQ","1694318113");
// 设置Cookie过期时间
cookie.setMaxAge(60*60*24*7);
// 响应
resp.addCookie(cookie); // 将Cookie添加至响应头
}
}
而SessionID是 Session会话追踪请求的主要原因
二、Session会话的销毁
1.服务器关闭
2.服务器重启
3.超出会话时间(可以自定义时间,默认为30分钟)
cookie.setMaxAge(60*60*24*7);(单位为秒)