JavaWeb~Servlet~In-depth understanding of cookies

What are cookies

The HTTP protocol itself is stateless, which means that there is no need to establish a persistent connection between the client and the server. That is, the client initiates a request to the server, and the server returns a response. After the response is returned, the connection is closed, and no information related to this connection is retained. That is, HTTP requests can only be initiated by the client to the server, and the server cannot send data to the client. That is, the server cannot identify the requested identity information.

A cookie is actually a small piece of text information, a string of strings organized in a key-value format.
After the client sends a request to the server, if the server needs to record the identity information of the request or record the user status, it will issue a cookie to the corresponding request. The URL and the cookie are sent to the server together, and the server checks the cookie to confirm the user's status.

This is similar to a bank card. When we go to the bank for business for the first time, the bank will give you a bank card. The card stores your identity information, phone number, password and other information. When you go to the bank, you can directly show your bank card to handle related business.
It is also like the medical card when you go to the hospital to see a doctor. When you go to see a doctor for the first time, you need to apply for a medical card. Your identity information, balance, etc. are stored in the card. to know your identity.

How Cookies Work

A cookie is a feature provided by the local browser that can store some data. Cookies are actually plain text stored in the browser. There will be a special cookie folder in the installation directory of the browser to store the cookies set under each domain.
When a web page wants to send a request, the browser will first check whether there is a response Cookie, and some are automatically added to the cookie field of the request header (request header). This process is automatically completed by the browser for us. The browser does this every time a request is made.

When we visit and log in to a website for the first time, the setting of cookies will go through the following steps:

  • Client sends request to server
  • The server returns the response + Set-Cookie field
  • Client saves cookies
  • When the client sends a request to the server, it will automatically add the cookie to the request header
  • The server recognizes the request identity information and sends the data directly.
    insert image description here
    We use the code to simply verify, create a new cookie in the doGet method, and access the packet capture observation.
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;

@WebServlet("/testCookie")
public class TestCookie extends HttpServlet {
    
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
        Cookie cookie=new Cookie("mcrwayfun",System.currentTimeMillis()+"");
        //设置生命周期为MAX_VALUE
        cookie.setMaxAge(Integer.MAX_VALUE);
        resp.addCookie(cookie);
    }
}

Capture the packet to view the request content, you can see that there is a Cookie in the request, and there is a Set-Cookie in the returned response.
insert image description here
insert image description here

Cookie attribute

The cookie itself has some attributes, such as when the cookie expires, which domain name, which path to send to, etc. When we set any cookie, we can set these related attributes, if not, we will use these The default value of the property. When set, properties are separated by a 分号and a 空格.

property item Introduction to property items
NAME=VALUE Key-value pair, you can set the Key/Value to be saved, note that this name cannot be the same as other attribute names
Expires Set the expiration date of the cookie
Domain Set the domain name, such as domain="www.sogou.com"
Path The path of the set cookie, such as path=/wp-admin/
Secure Set security, if this property is set, the cookie will only be sent when the SSH connection is made

Format example:

"key=name; expires=Thu, 25 Feb 2016 04:18:00 GMT; domain=ppsc.sankuai.com; path=/; secure; HttpOnly"

These properties are described in detail below:
expires
The expires option is used to set the expiration date of the cookie. When setting, expires must be set to the time in GMT format.
Setting the GMT time can be obtained by the new Date().toGMTString() method or the new Date().toUTCString() method

For example, expires=Thu,25 Feb 2020 04:18:00 GMT means that the cookie will expire after 4.18 minutes on February 25, 2020, and the expired cookie will be automatically cleared by the browser. If this option is not set, the default validity period is session, that is, session cookie, which will disappear after the browser is closed.

expires is an option in the http/1.0 protocol. It has been replaced by the max-age option in the new http/1.1 protocol. Both of them are used to limit the valid time of the cookie.

maxAge indicates the validity period of the cookie, in hours and seconds. Cookie provides two methods to operate this property, one is getMaxAge() and setMaxAge(int maxAge) to read and write this property.

There are three values ​​of max-age, positive, negative and 0 .

When the value of maxAge is positive, it means that the cookie will automatically expire after maxAge seconds. The browser will persist the cookie whose maxAge is a positive number, that is, write it to the local Cookie folder. Once written, whether the user closes the computer or the browser, as long as the time is still before maxAge seconds, the cookie will be saved when logging in to the website. still works.

Cookies like the code below are valid forever.

   Cookie cookie=new Cookie("mcrwayfun",System.currentTimeMillis()+"");
        //设置生命周期为MAX_VALUE
        cookie.setMaxAge(Integer.MAX_VALUE);
        resp.addCookie(cookie);

When the value of maxAge is negative, it means that the cookie is only a temporary cookie and will not be persisted, but only valid in the current window or sub-window. Once the browser is closed, the cookie will become invalid immediately.

        Cookie cookie = new Cookie("mcrwayfun",System.currentTimeMillis()+"");
        // MaxAge为负数,是一个临时Cookie,不会持久化
        cookie.setMaxAge(-1);
        resp.addCookie(cookie);

When maxAge is 0, it means that the cookie is deleted immediately

        Cookie[] cookies = req.getCookies();
        Cookie cookie = null;

        // get Cookie
        for (Cookie ck : cookies) {
    
    

            if ("mcrwayfun".equals(ck.getName())) {
    
    
                cookie = ck;
                break;
            }
        }

        if (null != cookie) {
    
    
            // 删除一个cookie
            cookie.setMaxAge(0);
            resp.addCookie(cookie);
        }

domain and path
domain is the domain name, path is the path, the sum of the two is the URL, domina and path limit the cookie can be accessed by those URLs.

Suppose we set the domain attribute of the cookie to sogou.com, if the domain name of the requested URL is "sogou.com" or its subdomains such as "api.baidu.com", "dev.api.baidu.com", and the URL The path is "/" or sub-paths "/home", "/home/login", the browser will add this cookie to the request's cookie header.

If neither of these properties are set, the default values ​​are used. The default value of domain will be set to the domain name of the webpage where the cookie is located. The default value of path will be set to the directory where the cookie page is located.

The secure
secure attribute is used to ensure that cookies are only sent in secure requests. In general, this attribute is empty by default. Whether it is HTTP or HTTPS protocol, cookies will be added to the request header. The cookie is added to the request only if the connection is SSH secure.

How we use cookies

Modify and delete cookies

The Cookie operation provided by HttpServletResponse has only one add operation: addCookie(Cookie cookie).
So if you want to modify a cookie, you can only use a cookie with the same name to overwrite the original cookie.
If you want to delete a cookie, you only need to create a new cookie with the same name, and Set its validity period maxAge to 0 and overwrite the original cookie.

Note that the new cookie, except value, maxAge, other attributes such as name, path, domain must be consistent with the original to achieve the effect of modification or deletion, otherwise the browser will consider it as two cookies and will not be overwritten.

set cookies

Cookies can be set by the client or by the server.

Server side settings

Whether the client requests a resource file or sends an ajax request, the server will return the response.
The set-cookie in the response header is specially used to set cookies. As shown in the
figure below, there are 5 set-cookie fields in the response header. Then each field will set a cookie correspondingly. The value of set-cookie is a normal string.
insert image description here
A set-Cookie field can only set one cookie. If you want to set multiple cookies, you need to add multiple set-Cookie fields. And in this field, you can set all the properties of the cookie.

Client Settings

On the client side, we can set it through JavaScript code.

The following code:

document.cookie = "name=Jonh; ";

In the console, we can see that the cookie is successfully set, and the default values ​​for domain, path, and expires are used.
insert image description here

If you want to set multiple cookies, the code is as follows:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<script>

  //设置了5个Cookie
    document.cookie = "name=Jonhs; ";
    document.cookie = "name=Jonh; age=12; class=111";
    document.cookie = "name=Jonh";
    document.cookie = "age=12";
    document.cookie = "class=111";
</script>
</body>
</html>

Setup succeeded.
insert image description here

What kind of data is suitable to put in cookies

The data stored in the cookie will be automatically placed in the http request by the browser every time. If the data does not need to be sent to the server every time the request is made, this automatic processing by the browser will undoubtedly increase the overhead, but if These data need to be sent to the server for each request, and this automatic processing by the browser helps us save a lot of repeated addition operations.
Therefore, the data required for each request is suitable to be placed in a cookie, such as typical authentication information, which is also commonly used to implement the web page login function.

The maximum cookie size under each domain name is 4KB, and the maximum number of cookies under each domain name is 20 (some browsers support more than 20)

Cookie format

The cookie itself is a string stored in the browser, and the format is similar to a key-value pair, consisting of key=value, and the key-value pair 分号is 空格separated by a and a.

Reference article:
https://blog.csdn.net/playboyanta123/article/details/79464684
https://www.jianshu.com/p/6fc9cea6daa2

Guess you like

Origin blog.csdn.net/Merciful_Lion/article/details/123601379