Cookie Overview-[Cookies and Sessions] It is guaranteed to be super easy to learn, I will doubt my life if I can’t learn it. .

About the session

  • What is a session? A
        session is a series of requests and responses that occur between the browser and the server.
        Session start: open the browser-visit JD.
        End of the session: close the browser
  • The data generated by the session
        will also generate some data during the interaction between the client and the server. In order to save the data generated during the session, in Servlet technology, two objects for saving session data are provided, namely Cookie and Session
  • The essence is the technology of accessing data in the browser or server

Cookie overview

    Cookie technology is to access session data on the browser side

Cookie characteristics

  • The data is in the form of key-value key-value pairs name=jack
  • The data has a survival time and can be modified
  • Some special symbols cannot be recognized, so this symbol needs to be transcoded (encoding and decoding)
  • A cookie can only store one key-value pair key-value
  • Cokie is a technology for the browser to save session data,

Cookie execution flow

Insert picture description here

  • (1) The browser visits the Servlet for the first time and creates a Cookie object (a key-value pair JSESSIONID is saved by default)
  • (2) Servlet sends the generated cookie to the browser
  • (3) Browser auto save
  • (4) The second visit to the server Servlet, the browser automatically puts the cookie data acquisition in the request

(1) Cookie creation
Cookie(String name, String value) Create cookie object
String getName() Get the name of the cookie
String getValue() Get the value of the cookie

Create and get cookies

  1. Cookie creation
        -Cookie(String name, String value) Create cookie object
        -String getName() to get the name of the cookie
        -String getValue() to get the value of the cookie

  2. Send the Cookie to the server
        response.addCookie(Cookie cookie);

  3. Get
        Cookie Cookie[] getCookies() Get the cookies sent by the browser
        Cookie[] cookies = request.getCookies(); (If there is no cookie, it will return a null)

Realization case

By SetCookieServletsetting cookies, then by GetCookieServletobtaining cookies.

@WebServlet("/SetCookieServlet")
public class SetCookieServlet extends HttpServlet {
    
    
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        //一个cookie只能存储一个键值对key-value cokie是浏览器保存会话数据的技术,
        //保存cookie,保存账号密码,第二次的时候,浏览器会自动放到request请求中 将其带数据到服务器里面并显示,自动验证
        //1、创建cookie 一个cookie只有一个键值对
        Cookie cookie1 = new Cookie("username", "Strive_GF");
        Cookie cookie2 = new Cookie("password", "123456");

        //2、将Cookie发送给浏览器 
        response.addCookie(cookie1);
        response.addCookie(cookie2);
    }
}
@WebServlet("/GetCookieServlet ")
public class GetCookieServlet extends HttpServlet {
    
    
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    

        //获取cookie ,第二次开始访问网站,此时浏览器会自动地将保存的cookie放到请求带到Servlet
        Cookie[] cookies = request.getCookies();//一个cookie都没有 getCookie()方法返回的是null

        if(cookies != null){
    
    
            //循环所有的cookie
            for(Cookie cookie:cookies){
    
    
                System.out.println(cookie.getName()+" : "+cookie.getValue());
            }
        }else{
    
    
            System.out.println("没有查询到cookie");
        }
    }
}

operation result:

  1. Run directly GetCookieServlet
    Insert picture description here
    2. Run first SetCookieServletto set the cookie value, and then GetCookieServletget the cookie value
    Insert picture description here
  2. GetCookieServletGet the cookie directly through the URL address after closing the browser
    Insert picture description here

Cookie lifetime

void setMaxAge(int expiry) Set the maximum cookie lifetime (unit: second)
    (1) By default, the cookie lifetime in the browser is a session
    (2) Sometimes we need to set the cookie lifetime
if you set it setMaxAge, Cookie will be saved in the hard disk according to the survival time

Case realization

@WebServlet("/SetMaxAgeServlet")
public class SetMaxAgeServlet extends HttpServlet {
    
    

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        //创建cookie对象
        Cookie cookie1 = new Cookie("username","Strive_GF");
        Cookie cookie2 = new Cookie("password","1234");

        //设置cookie的存活时间 单位是秒,这里是一天
        cookie1.setMaxAge(24*60*60);
        cookie2.setMaxAge(24*60*60);
        //将cookie发送给服务器  因为cookie是浏览器保存会话数据的技术 ,所以必须将cookie发给浏览器
        response.addCookie(cookie1);
        response.addCookie(cookie2);
    }
}

operation result:

  1. Run to SetMaxAgeServletset cookies, and GetCookieServletget cookies through the above
    Insert picture description here
  2. Close the browser again and passGetCookieServlet
    Insert picture description here

Cookie access path

  • void setPath(String uri)
        Set the cookie path-the browser will determine which cookies to send to the server based on this path. If it is not the cookie under this server, it will not be sent to the server (for example: Taobao, Jingdong, you have set automatic Login, the account is the same but the password is different, this time you need to set this access path to send the corresponding cookie to the corresponding server)
  1. Method 1: /webName/ When accessing all resources under the webName project, the request will carry Cookie** [default method]**
  2. Method 2: /webName/user When accessing all resources under the user module under the webName project, the request will carry Cookie
  3. Method 3: / When accessing all resources in the server, the request will carry Cookie

Case realization

@WebServlet("/SetPathServlet")
public class SetPathServlet extends HttpServlet {
    
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        //创建cookie对象
        Cookie cookie1 = new Cookie("username","Strive_GF_SetPathServlet");
        Cookie cookie2 = new Cookie("password","123456");

        //设置cookie的存活时间 单位是秒,这里是一天
        cookie1.setMaxAge(24*60*60);
        cookie2.setMaxAge(24*60*60);

        //request.getContextPath() 获取当前项目名称 设置
        cookie1.setPath(request.getContextPath());
        cookie2.setPath(request.getContextPath());
        //将cookie发送给服务器  因为cookie是浏览器保存会话数据的技术 ,所以必须将cookie发给浏览器
        response.addCookie(cookie1);
        response.addCookie(cookie2);
    }
}
@WebServlet("/SetPath_TaoBao_Servlet")
public class SetPath_TaoBao_Servletextends HttpServlet {
    
    
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        //创建cookie对象
        Cookie cookie1 = new Cookie("username","SetPath_TaoBao_Servlet");
        Cookie cookie2 = new Cookie("password","123456");

        //设置cookie的存活时间 单位是秒,这里是一天
        cookie1.setMaxAge(24*60*60);
        cookie2.setMaxAge(24*60*60);

		//将cookie访问路径设置为/taobao
        cookie1.setPath("/taobao");
        cookie2.setPath("/taobao");
        //request.getContextPath() 获取当前项目名称 设置
//        cookie1.setPath(request.getContextPath());
//        cookie2.setPath(request.getContextPath());

        //将cookie发送给服务器  因为cookie是浏览器保存会话数据的技术 ,所以必须将cookie发给浏览器
        response.addCookie(cookie1);
        response.addCookie(cookie2);
    }
}

operation result:

  1. By SetPathServletsetting the project’s access path to the current project path, and then GetCookieServletobtaining
    Insert picture description here
  2. First run SetPath_TaoBao_Servletcookie.setPath("/taobao") and then run to GetCookieServletget cookie
    Insert picture description here

Cookie removal

There is no way to clear cookies, but the purpose of clearing cookies can be achieved in the following two ways:

  1. You can modify the survival time to 0 and
        set the cookie lifetime to 0 (cookie.setMaxAge(0))
  2. You can use a null value to overwrite the original value to achieve the purpose of clearing the cookie. The latter is used to overwrite the cookie. The name and path must be the same as the original cookie.
        Create a cookie again, the key is the same as the original one, and the value is set to "" null value. Achieve clearing effect

Case realization

//1、修改存活时间为0

@WebServlet("/ClearCookieServlet_1")
public class ClearCookieServlet_1 extends HttpServlet {
    
    
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        //创建cookie对象
        Cookie cookie1 = new Cookie("username","ClearCookieServlet_1");
        Cookie cookie2 = new Cookie("password","123456");
        //设置cookie的存活时间为0  也就是创建即销毁
        cookie1.setMaxAge(0);
        cookie2.setMaxAge(0);
        
        //将cookie发送给服务器
        response.addCookie(cookie1);
        response.addCookie(cookie2);
    }
}
//2、使用空值覆盖原值的方法来达到清除cookie的目的

@WebServlet("/ClearCookieServlet_2")
public class ClearCookieServlet_2 extends HttpServlet {
    
    

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        //通过值覆盖 设置cookie中对应的key的值为""空来达到清除cookie的目的
        Cookie cookie1 = new Cookie("username","");
        Cookie cookie2 = new Cookie("password","");

        cookie1.setMaxAge(24*60*60);
        cookie2.setMaxAge(24*60*60);
        //发送给服务器
        response.addCookie(cookie1);
        response.addCookie(cookie2);
    }
}

operation result

  1. By ClearCookieServlet_1modifying the cookie survival time to 0, then GetCookieServletobtaining the cookie
    Insert picture description here
  2. By ClearCookieServlet_2overwriting the value of the cookie to a null value "", and then calling to GetCookieServletget the cookie.
    Insert picture description here
    Note: It is recommended to use the first method to clear the cookie, and the second method is just null overwrite

Cookie encoding problem

the reason:

  1. Cookie cannot recognize some special symbols, so it is necessary to transcode (encode and decode) this symbol to prevent some unrecognized garbled characters from being written first
        -encoding: URLEncoder.encode(date, "UTF-8")
        -decoding: URLDecoder. decode(date, “UTF-8”)
  2. Some value cookies cannot be saved, then encode first and save

Case realization

  1. Let’s first look at the phenomenon of no transcoding
@WebServlet("/EncodeServlet")
public class EncodeServlet extends HttpServlet {
    
    
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    

        //创建cookie对象
        Cookie cookie1 = new Cookie("username", URLEncoder.encode("我叫浪夏一学 2020年9月12日17:43:02"));
        Cookie cookie2 = new Cookie("password", URLEncoder.encode("中国1234"));
        //设置cookie对象存活期
        cookie1.setMaxAge(24*60*60);
        cookie2.setMaxAge(24*60*60);
        //发送给服务器
        response.addCookie(cookie1);
        response.addCookie(cookie2);
    }
}

By EncodeServletsetting the cookie, and then by GetCookieServletobtaining
Insert picture description here
2. Through encode and decode encoding and decoding to achieve

@WebServlet("/EncodeServlet")
public class EncodeServlet extends HttpServlet {
    
    
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    

        //创建cookie对象
//        Cookie cookie1 = new Cookie("username", URLEncoder.encode("我叫浪夏一学 2020年9月12日17:43:02"));
//        Cookie cookie2 = new Cookie("password", URLEncoder.encode("中国1234"));
        //通过URLEncoder.encode()编码
        Cookie cookie1 = new Cookie("username", URLEncoder.encode("我叫浪夏一学 2020年9月12日17:43:02","utf-8"));
        Cookie cookie2 = new Cookie("password", URLEncoder.encode("中国1234","utf-8"));
        //设置cookie对象存活期
        cookie1.setMaxAge(24*60*60);
        cookie2.setMaxAge(24*60*60);
        //发送给服务器
        response.addCookie(cookie1);
        response.addCookie(cookie2);
    }
}
@WebServlet("/DecodeServlet")
public class DecodeServlet extends HttpServlet {
    
    
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    

        //获取cookie数组
        Cookie[] cookies = request.getCookies();
        if(cookies != null){
    
    
            //循环所有的cookie
            for(Cookie cookie:cookies){
    
    
                //URLDecoder.decode()对其解码
                System.out.println(cookie.getName()+" "+ URLDecoder.decode(cookie.getValue(),"utf-8"));
            }
        }else{
    
    
            System.out.println("没有查询到cookie");
        }
    }
}

Operation result:
first EncodeServletencode it, then DecodeServletdecode output
Insert picture description here

Guess you like

Origin blog.csdn.net/qq_40542534/article/details/108550057