到底创建了几个Session

重点: 每个客户端都有自己的一个 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());
    }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值