重点: 每个客户端都有自己的一个 Session 会话,Session默认超时时间为30分钟。
问题:
1、在同一个浏览器新打开一个tab卡,访问同一站点,此时几个session
2、将新打开的tab卡拖拽出来,成为两个浏览器的时候,创建了几个session
3、换一个浏览器,访问同一个站点,此时几个session
先说结论:
1.对于同一个浏览器,在不清除cookie、缓存、关闭浏览器的前提下,如果没到失效时间,session都是同一个
2.拖拽出来之后,session依然是同一个
3.换一个浏览器,session改变
session存在于服务端,由于http是无状态的,服务端无法区别请求由哪个客户端发送,最终还是依赖cookie(上述结论同样适用于cookie),每次发送请求携带一个JSESSIONID,即服务端获取的sessionId,唯一标识一个客户端请求。
测试代码如下:
@GetMapping("/session")
protected void createSession(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
HttpSession session = req.getSession();
session.setAttribute("key1", "value1");
// 设置当前Session3秒后超时
session.setMaxInactiveInterval(3); // 值设置为-1,像是永不超时?
// 判断 当前Session会话,是否是新创建出来的
boolean isNew = session.isNew();
// 获取Session会话的唯一标识 id
String id = session.getId();
resp.setContentType("text/html; charset=UTF-8");
resp.getWriter().write("得到的Session,它的id是:" + id + " <br /> ");
resp.getWriter().write("这个Session是否是新创建的:" + isNew + " <br /> ");
}
@GetMapping("/getSession")
protected void getSession(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Object key1 = req.getSession().getAttribute("key1");
resp.setContentType("text/html; charset=UTF-8");
resp.getWriter().write("这个Session是:" + key1 + " <br /> ");
}
@GetMapping("/cookie")
void cookie(HttpServletRequest req, HttpServletResponse resp) throws IOException {
resp.setContentType("text/html; charset=UTF-8");
Cookie cookie = new Cookie("path1", "path2");
// 如果设置为负值的话,则为浏览器进程Cookie(内存中保存),关闭浏览器就失效;如果设置为0,则立即删除该Cookie。
cookie.setMaxAge(60 * 60); // 设置Cookie一小时之后被删除。(每次请求不会刷新时长)
// Cookie 有效路径 Path 的设置
cookie.setPath( req.getContextPath() + "/getcookie" ); // ===>>>> /工程路径/abc
resp.addCookie(cookie);
resp.getWriter().write("创建了一个带有Path路径的Cookie");
}
@GetMapping("/getcookie")
void getcookie(HttpServletRequest req, HttpServletResponse resp) throws IOException {
resp.setContentType("text/html; charset=UTF-8");
Cookie cookie = findCookie("path1", req.getCookies());
resp.getWriter().write("得到的Cookie值是"+ cookie.getValue());
}