Super detailed explanation of cookie life cycle and cookie effective path

Super detailed explanation of cookie life cycle and cookie effective path

cookie life cycle

introduce

  1. The life cycle of cookies refers to how to manage when cookies are destroyed (deleted)

  2. setMaxAge()

​ ● Positive number, indicating to expire after the specified number of seconds

​ ● A negative number means that the cookie will be deleted when the browser is closed (the default value is -1)

​ ● 0, means delete the cookie immediately

code example

public class CookieLive extends HttpServlet {
    
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        System.out.println("CookieLive 被调用...");

        //演示创建一个cookie , 生命周期为 60s
        Cookie cookie = new Cookie("job", "java");
        //解读:
        // 1. 从创建该cookie开始计时, 60秒后无效
        // 2. 浏览器来根据创建的时间,计时到60s秒,就认为该cookie无效
        // 3. 如果该cookie无效,那么浏览器在发出http请求时,就不在携带该cookie
        cookie.setMaxAge(60);
        //将cookie保存到浏览器
        response.addCookie(cookie);


        //演示如何删除一个cookie, 比如删除username
        //1 先得到username cookie
        Cookie[] cookies = request.getCookies();
        Cookie usernameCookie =
                CookieUtils.readCookieByName("username", cookies);
        if(usernameCookie != null) {
    
    
            //2. 将其生命周期设置为0
            usernameCookie.setMaxAge(0);
            //3. 重新保存该cookie, 因为你将其生命周期设置0, 就等价于让浏览器删除该cookie
            //4. 说明:该cookie会被浏览器直接删除
            //   返回一个Set-Cookie: xxxxx => 一会抓包.
            //   Set-Cookie: username=tom; Expires=Thu, 01-Jan-1970 00:00:10 GMT
            response.addCookie(usernameCookie);//返回一个Set-Cookie: xxxxx => 一会抓包.
        }else{
    
    
            System.out.println("没有找到该cookie, 无法删除...");
        }

        /***********************
         * 默认的会话级别的 Cookie [即浏览器关闭就销毁了]
         * 前面我们讲课时,都是默认会话级别的生命周期
         ***********************/
        Cookie cookie3 = new Cookie("dkey", "dkey_value");
        /**
         * 解读 setMaxAge源码
         * public void setMaxAge(int expiry) {
         *         this.maxAge = expiry;
         * }
         * private int maxAge = -1; 默认就是-1
         */
        //cookie.setMaxAge(-1);//设置存活时间
        response.addCookie(cookie3);


        // 给浏览器返回信息
        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.println("<h1>设置cookie生命周期</h1>");
        writer.flush();
        writer.close();

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        doPost(request, response);
    }
}

Complete the test, pay attention to packet capture to see the data

insert image description here

cookie valid path

valid path rules

  1. Cookie effective path Path setting

  2. The path attribute of Cookie can effectively filter which Cookies can be sent to the server. Which ones are not posted. The path attribute is effectively filtered by the requested address

The rules are as follows:

cookie1.setPath = /project path

cookie2.setPath = /project path/aaa

Request address: http://ip:port/project path/resource

cookie1 will be sent to the server

cookie2 will not be sent to the server

Request address: http://ip:port/project path/aaa/resource

cookie1 will be sent to the server

cookie2 will be sent to the server

code example

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class CookiePathServlet extends HttpServlet {
    
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
    
    
        doGet(request, response);
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
    
    
        Cookie cookie = new Cookie("keyPath1", "keyPath1Value");
        // request.getContextPath() + "/aaa" 得到 /工程路径/aaa
        cookie.setPath(request.getContextPath() + "/aaa");
        Cookie cookie2 = new Cookie("keyPath2", "keyPath2Value");
        cookie2.setPath(request.getContextPath());
        response.addCookie(cookie);
        response.addCookie(cookie2);
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().write("<h1>创建 Cookie keyPath1 路径 /工程路径/aaa </h1>");
        response.getWriter().write("<h1>创建 Cookie keyPath2 路径 /工程路径 </h1>");
    }
}

After completing the test, pay attention to capture the packet to see the returned data when creating the cookie

insert image description here

After completing the test, pay attention to capture the packet to see the returned data when reading the cookie

insert image description here

code example

Requirement: Complete the application case of automatically filling in the login account. If the user logs in successfully, the login account will be automatically filled in the next login

html page

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>登录页面</title>
</head>
<body>
<h1>用户登录界面</h1>
<form action="#" method="post">
    u:<input type="text" name="username"><br/>
    p:<input type="password" name="pwd"><br/>
    <input type="submit" value="登录">
</form>
</body>
</html>

Create LoginServlet

public class LoginServlet extends HttpServlet {
    
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        //System.out.println("LoginServlet 被调用...~~~");

        //1. 接收表单提交用户名和密码
        String username = request.getParameter("username");
        String pwd = request.getParameter("pwd");

        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = response.getWriter();
        //2. 判断是否合法
        if ("xxxx".equals(username) && "123456".equals(pwd)) {
    
    
            //将登录成功的用户名,以cookie的形式,保存到浏览器
            Cookie loginuserCookie = new Cookie("loginuser", username);
            //设置该cookie生命周期
            loginuserCookie.setMaxAge(3600 * 24 * 3);
            response.addCookie(loginuserCookie);
            //合法
            writer.println("<h1>登录OK</h1>");

        } else {
    
    
            //不合法
            writer.println("<h1>登录失败</h1>");
        }

        writer.flush();
        writer.close();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        doPost(request, response);
    }
}

Cookie considerations and details

  1. A cookie can only identify one kind of information, and it contains at least a name (NAME) and setting value (VALUE) to identify the information.

  2. A WEB site can send multiple cookies to a browser, and a browser can also store cookies provided by multiple WEB sites.

  3. The total number of cookies is not limited, but the number of cookies for each domain name and the size of each cookie are limited (different browsers have different restrictions, just know it), and cookies are not suitable for storing information with a large amount of data.

  4. Note that when deleting cookies, the paths must be consistent, otherwise they will not be deleted

  5. Chinese garbled characters in cookie in Java servlet

Note If you store Chinese cookies, an error will be reported by default, which can be solved by URL encoding and decoding. It is not recommended to store Chinese cookie information

code solution

set up

public class EncoderCookie extends HttpServlet {
    
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        //System.out.println("EncoderCookie 被调用");
        //1. 创建cookie, 有中文

        //1) 如果直接存放中文的cookie, 报错 Control character in cookie value or attribute.
        //2) 解决方法,就是将中文 编程成 URL编码  英文: Encode=编码
        //3) 编码后,再保存即可
        String company = URLEncoder.encode("大家好", "utf-8");

        Cookie cookie = new Cookie("company", company);
        //2. 保存到浏览器
        response.addCookie(cookie);

        //3. 给浏览器返回信息
        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.println("<h1>设置中文cookie成功</h1>");
        writer.flush();
        writer.close();

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        doPost(request, response);
    }
}

decoding

public class ReadCookie2 extends HttpServlet {
    
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    

        System.out.println("ReadCookie2 被调用..");
        //读取到中文cookie
        Cookie[] cookies = request.getCookies();
        Cookie companyCookie = CookieUtils.readCookieByName("company",cookies);
        String companyVal = companyCookie.getValue();
        System.out.println("companyVal= " + companyVal);//URL

        //解码
        companyVal = URLDecoder.decode(companyVal, "utf-8");
        System.out.println("解码后 companyVal= " + companyVal);//中文

        //3. 给浏览器返回信息
        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.println("<h1>读取中文cookie解码成功~</h1>");
        writer.flush();
        writer.close();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        doPost(request,response);
    }
}

Guess you like

Origin blog.csdn.net/apple_67445472/article/details/131772776