• 【Web入门系列】初探会话管理-Cookie


    特点

    会话数据保存在浏览器客户端。

    Cookie技术核心

    1、构造Cookie对象

      Cookie(String name, String value)

    2、设置cookie

      #设置cookie的有效访问路径

      void setPath(String uri)

      #设置cookie的有效时间

      void setMaxAge(int expiry) : 

      #设置cookie的值

      void setValue(String value) :

    3、发送cookie到浏览器端保存

      void response.addCookie(Cookie cookie)

    4、服务器接收cookie

      Cookie[] request.getCookies()

    Cookie原理

    1、服务器创建cookie对象,把会话数据存储到cookie对象中;2、服务器发送cookie信息到浏览器;3、浏览器得到服务器发送的cookie,然后保存在浏览器端。

    4、浏览器在下次访问服务器时,会带着cookie信息;5、服务器接收到浏览器带来的cookie信息。

    public class CookieServlet extends HttpServlet {
    
        @Override
        public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
            // 1、创建Cookie对象
            Cookie cookie = new Cookie("name","ss");
    
            // 2、把cookie数据发送到浏览器(通过响应头发送: set-cookie名称)
            //response.setHeader("set-cookie", cookie.getName()+"="+cookie.getValue());
            //推荐使用这种方法,避免手动发送cookie信息
            response.addCookie(cookie);
        }
    }
    public class GetCookieServlet extends HttpServlet {
    
        @Override
        public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
            // 3、接收浏览器发送的cookie信息
            Cookie[] cookies = request.getCookies();
            if (cookies != null){
                for (Cookie cookie : cookies){
                    String name = cookie.getName();
                    String value = cookie.getValue();
                    System.out.println(name+"="+value);
                }
            }
        }
    }

    Cookie细节

    public class CookieServlet extends HttpServlet {
    
        @Override
        public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
            // 1、创建Cookie对象
            Cookie cookie = new Cookie("name","ss");
    
            /**
             * 1)设置cookie的有效路径。默认情况:有效路径在当前web应用下。 /myweb
             */
            //cookie.setPath("/myweb");
    
            /**
             * 2)设置cookie的有效时间
             * 正整数:表示cookie数据保存浏览器的缓存目录(硬盘中),数值表示保存的时间。
             * 负整数:表示cookie数据保存浏览器的内存中,浏览器关闭cookie数据丢失。
             * 零:表示删除同名的cookie数据
             */
            //cookie.setMaxAge(20);
            //cookie.setMaxAge(-1); 
            //cookie1.setMaxAge(0);
            
            //2.把cookie数据发送到浏览器(通过响应头发送: set-cookie名称)
            //response.setHeader("set-cookie", cookie.getName()+"="+cookie.getValue());
            //推荐使用这种方法,避免手动发送cookie信息
            response.addCookie(cookie);
        }
    }

    注意:Cookie数据类型只能保存非中文字符串类型的。可以保存多个cookie,但是浏览器一般只允许存放300个Cookie,每个站点最多存放20个Cookie,

    每个Cookie的大小限制为4KB。

    Cookie应用案例-获取上次访问时间

    public class CookieHisServlet extends HttpServlet {
    
        public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            response.setContentType("text/html;charset=utf-8");
    
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            String curTime = format.format(new Date());
    
            Cookie[] cookies = request.getCookies();
            String lastTime = null;
            if(cookies != null){
                for (Cookie cookie : cookies) {
                    if(cookie.getName().equals("lastTime")){
                        lastTime = cookie.getValue();
                        response.getWriter().write("欢迎回来,你上次访问的时间为:"+ URLDecoder.decode(lastTime,"UTF-8")+",当前时间为:"+curTime);
                        cookie.setValue(URLEncoder.encode(curTime,"UTF-8"));
                        cookie.setMaxAge(1*30*24*60*60);
                        response.addCookie(cookie);
                        break;
                    }
                }
            }
    
            if(cookies == null || lastTime == null){
                /**
                 * 当cookie中包含有等号、空格、分号等特殊字符时,可能会导致数据丢失、或者不能解析的错误,
                 * 一个较好的解决办法就是:在将cookie值写入客户端浏览器之前,首先进行URLEncode编码,
                 * 读取cookie时,进行URLDecode即可。
                 */
                response.getWriter().write("你是首次访问本网站,当前时间为:"+curTime);
                Cookie cookie = new Cookie("lastTime",URLEncoder.encode(curTime,"UTF-8"));
                cookie.setMaxAge(1*30*24*60*60);
                response.addCookie(cookie);
            }
        }
    }
  • 相关阅读:
    Websocket基础知识简记
    jmeter websocket接口测试
    软件测试的艺术 笔记(上)
    错误提示Unable to preventDefault inside passive event listener解决方法
    vue-cil3关闭eslint语法检查
    mongoDB无法启动服务器
    Vue之todoList
    react踩坑第一章
    父组件向孙子组件传值(Context)特性
    变量声明
  • 原文地址:https://www.cnblogs.com/ysdrzp/p/9879745.html
Copyright © 2020-2023  润新知