zoukankan      html  css  js  c++  java
  • Cookie

    概念:客户端会话技术,将数据保存到客户端

    浏览器会自动存储Cookie,下一次请求会自动带着Cookie

    使用步骤

      1.创建Cookie对象,绑定数据(第一次请求)

    new Cookie(String name,String value)

      2. 发送Cookie对象(响应)

    response.addCookie(Cookie cookie)

      3.获取Cookie对象,拿到数据(第二次请求)

    Cookie[] request.getCookie()

     内部使用map的结构来存储数据

    package cn.itcast.cookie;
    
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.Cookie;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    
    /**
     * @author 旗木五五开
     * @create 2020-03-23 16:55
     * 快速入门
     */
    @WebServlet("/cookieDemo1")
    public class CookieDemo1 extends HttpServlet {
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    //        1.创建Cookie对象
            Cookie c = new Cookie("msg", "hello");
    //        2.发送Cookie(浏览器返回)
            response.addCookie(c);
        }
    
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            this.doPost(request, response);
        }
    }
    package cn.itcast.cookie;
    
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.Cookie;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    
    /**
     * @author 旗木五五开
     * @create 2020-03-23 17:01
     */
    @WebServlet("/cookieDemo2")
    public class CookieDemo2 extends HttpServlet {
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    //        3.获取Cookie
            Cookie[] cs = request.getCookies();
    //        获取数据,遍历Cookies
            if (cs!=null){
                for (Cookie c : cs) {
                    String name = c.getName();
                    String value = c.getValue();
                    System.out.println(name+":"+value);
                }
            }
        }
    
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            this.doPost(request, response);
        }
    }

     

     这时候用其他浏览器访问demo2控制台上不会输出内容。因为cookie为空

  • 相关阅读:
    python爬取酷狗音乐
    python爬取酷我音乐
    排列组合+逆元模板
    python爬取QQVIP音乐
    一维数组的动态和
    买卖股票的最佳时机 II
    最佳买卖股票时机含冷冻期
    买卖股票的最佳时机
    子集
    最短无序连续子数组
  • 原文地址:https://www.cnblogs.com/rijiyuelei/p/12552702.html
Copyright © 2011-2022 走看看