Cookie和Session

Cookie和Session

会话

  • 会话:用户打开一个浏览器,点击了很多超链接,访问多个web资源,关闭浏览器的过程

  • 有状态会话

    • cookie:服务器给客户端一个信件,客户端下次访问服务器带上信件就可以了
      • 客户端技术(响应,请求)
    • session:服务器登记你来过了,下次你来的时候我匹配你
      • 服务器技术,保存用户的会话信息
//保存用户上一次访问的时间
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //解决中文乱码
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setHeader("Content-Type", "text/html;charset=utf-8");
        //获取输出流
        PrintWriter out = resp.getWriter();
        //服务器端从客户端获取Cookie
        Cookie[] cookies = req.getCookies();
        //判断Cookie是否存在
        boolean flag = false;
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                //判断Cookie
                if (cookie.getName().equals("lastLoginTime")) {
                    flag = true;
                    //获取Cookie中的值,转换为时间
                    out.write("你上一次访问的时间是:");
                    out.write(new Date(Long.parseLong(cookie.getValue())).toLocaleString());
                }
            }
        }
        if (!flag) {
            out.write("这是您第一次访问本站");
        }
        //服务器给客户端响应一个Cookie
        Cookie cookie = new Cookie("lastLoginTime", System.currentTimeMillis() + "");
        //Cookie有效期为1天
        cookie.setMaxAge(24 * 60 * 60);
        resp.addCookie(cookie);
    }

Session

  • 服务器会给每个用户(浏览器)创建一个Session对象

  • 一个Session独占一个浏览器,只要浏览器没有关闭,这个Session就存在

  • Session和Cookie的区别:

    • Cookie是把用户的数据写给用户的浏览器,浏览器保存(可以保存多个)
    • Session把用户的数据写到用户独占的Session中,服务器保存(保存重要的信息,减少服务器资源的浪费)
    • Session对象由服务器创建
  • 使用场景:

    • 保存一个登陆用户的信息
    • 购物车信息
    • 在整个网站中经常会使用的数据
  • 基本方法:req.getSession()、session.getId()、session.setAttribute()、session.getAttribute()、session.removeAttribute()、sessoion.invalidate()

  • 会话自动过期:

    • <session-config>
          <session-timeout>time</session-timeout>
      </session-config>
      
posted @ 2021-01-28 14:31  一天到晚睡觉的鱼  阅读(52)  评论(0)    收藏  举报