聊聊Session和Cookie

1.首先聊聊Cookie
cookie:

  • 一般会保存在本地的用户目录下appdata
  • 一个Cookie只能保存一个信息;
  • 一个web站点可以给浏览器发送多个cookie,最多存放20个cookie;
  • cookie大小有限制4kb;
  • 300个cookie浏览器上线;
    删除Cookie
  • 不设置有效期,关闭浏览器,自动失效;
  • 设置有效期时间为0;
public class SetCookieServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request,response);//调入当前类的doget方法
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html");
        Cookie pedCookie=new Cookie("password","root");
        pedCookie.setMaxAge(-1);
        //-1表示此cookie为永久响应
        response.addCookie(pedCookie);

        Cookie gwlCookie = new Cookie("gwl","lxj");
        gwlCookie.setMaxAge(60);
        response.addCookie(gwlCookie);


        Cookie wcCookie = new Cookie(URLEncoder.encode("旺财","UTF-8"),"lxj");
        gwlCookie.setMaxAge(60);
        response.addCookie(gwlCookie);
        //服务端从客户端取值
        PrintWriter writer=response.getWriter();
        Cookie[] cookies = request.getCookies();
        if(cookies !=null){
            writer.write("你上一次访问的时间是:");
            for (int i = 0; i < cookies.length; i++) {
                Cookie cookie = cookies[i];
                if(cookie.getName().equals("gwl")){
                    writer.write(URLDecoder.decode(cookie.getValue(),"UTF-8"));
                }
            }
        }else {
            writer.write("这是你第一次访问");
        }


        writer.println("<h1>cookie写入成功~</h1>");
    }
}

2.聊聊Session

什么是session:

  • 服务器给每一个用户(浏览器)创建一个对象;
  • 一个session独占一个浏览器,只要浏览器没有关闭,这个session就存在;
  • 用户登录之后,整个网站它都可以访问:保存用户信息,保存购物车信息;
public class MySessionServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html");
        PrintWriter writer = response.getWriter();

        // 操作 Session,尝试从客户端获取一个 session,如果获取
        // 失败,这新创建一个session信息
        HttpSession session = request.getSession();
        //服务器做校验
        String sessionId = session.getId();
        writer.println("<h1>欢迎访问~</h1>");
        writer.println(String.format("<h3>SessionID:%s</h3>",
                sessionId));
        writer.println("<hr>"); // 输出分隔线

        // 打印 Session 的创建时间
        writer.println("Session 创建时间:"+ LocalDateTime.ofInstant(Instant.ofEpochMilli(session.getCreationTime()), ZoneId.systemDefault()));

        // 打印 Session 的最后访问时间
        writer.println(String.format("<p></p>Session 最后访问时间:%s<p></p>",
                LocalDateTime.ofInstant(Instant.ofEpochMilli(session.getLastAccessedTime()), ZoneId.systemDefault())));

        // 会话 key 值定义
        String sessionKey = "countkey";
        // 判断当前会话信息session是否为新的会话信息
        if(session.isNew() ||
                session.getAttribute(sessionKey)==null){
            // 表示第一次使用 session 对象
            session.setAttribute(sessionKey,1);
            writer.println("访问次数:1");
        }else{
            // 非第一次访问
            int count =(int)session.getAttribute(sessionKey);
            count++;
            // 更新 session 信息
            session.setAttribute(sessionKey,count);
            writer.println("访问次数:"+count);
        }
       // 移除属性
//        session.removeAttribute("countkey");
//        //设置过期
//        session.invalidate();
    }
}

Sesion和Cookie的区别:

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

使用场景:

  • 保存一个登录用户的信息;
  • 购物车信息;
  • 在整个网站中经常会使用的数据,我们将它保存在session中;
  • 12
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值