In-depth understanding of Cookie (practical, praise)

Original Source: https://www.jianshu.com/p/6fc9cea6daa2

j-kelly-brito-416262-unsplash.jpg

1 Introduction

A friend asked me what cookie is used to doing, but I actually can not clearly understand the brief to its elaborate cookie, which can not help but let me thinking: Why I can not explain, I had doubts about the method of learning! Some people know almost see in the recommended Fellman learning skills, so use this technique in the process of re-learning the cookie to test the effect to be verified!

Before learning a new knowledge, we should understand their own learning goals, learning to go with doubt, this section need to know:

  1. What is a cookie, cookie role
  2. the cookie mechanism that cookie is operational processes
  3. cookie basic properties (4) and how we use cookie

2. What is a cookie

HTTP protocol itself is stateless. What it is stateless, that server can not determine the user's identity. Cookie is actually a short text message (key-value format). The client initiates a request to the server, if users need to record the state, issued a response on the use of Cookie to the client browser. Cookie client browser will be saved. When a browser requests that site again, the browser URL along with the request submitted with the Cookie to the server. The server checks the Cookie, in order to identify user state.

Figuratively, we went to the bank for savings business, the first time you do a bank card, which kept the identity card, password, mobile phones and other personal information. When you come again to this bank, bank machine can identify your card, which can directly conduct business.

3. cookie mechanism

When the user first visits a site and log in, cookie settings and will send through the following four steps:

The client sends a request to the server - " server sends a response to the client HttpResponse, which comprises a Set-Cookie header -" client save Cookie, after sending the request to the server, the request will include the HttpRequest of a Cookie head - " server returns response data

image

To explore this process, write test code, as follows:

I doGet method, new a Cookie object and add it to the HttpResponse object

 

    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);
    }

Browser to access the input address, as shown in FIG Results:

image

Visible Response Headers Set-Cookie header contains, and Request Headers contains the Cookie header. name and value is the above settings.

4. cookie attribute items

Property item Property item description
NAME=VALUE Key-value pairs can be set to save the Key / Value, can not pay attention to where the NAME and the name of the other attributes of the same item
Expires Expiration time, after a certain point in time set by the Cookie will fail
Domain Cookie generating the domain, such as = Domain " www.baidu.com "
Path The Cookie is generated in which the current path, such as path = / wp-admin /
Secure If this property is set, it will only return when the Cookie SSH connection

Expires

This is used to set the validity period of the Cookie. Cookie in maxAge attribute used to indicate the seconds. Cookie to read and write in this property by getMaxAge () and setMaxAge (int maxAge). maxAge There are three values, namely a positive, negative, and 0.

If maxAge attribute is positive, it indicates that the Cookie will automatically expire after maxAge seconds. Browser will maxAge Cookie is a positive number of persistence, i.e. the file is written to the corresponding Cookie (position of each browser stores inconsistent). Whether a customer closes the browser or computer, as long as before still maxAge seconds, visit the website of the Cookie is still valid. Cookie The following code will always be valid.

 

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

When maxAge attribute is negative, it indicates that the Cookie Cookie is a temporary, not persisted, valid only in this sub-window or the browser window of the present window is open, the Cookie fail immediately after the browser is closed.

 

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

You can see that when MaxAge is -1, the time has expired

image

When maxAge is 0, which indicates immediately delete Cookie

 

        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);
        }

So what is the difference maxAge set to a negative value and 0 in the end have it?

maxAge set to 0 indicates to delete the Cookie Now, if in debug mode, performing the above method, can immediately see the cookie is deleted.

image

maxAge set to a negative number, you can see Expires attribute has changed, but the Cookie will still be some time until the browser is closed or re-open the browser.

image

Modify or delete Cookie

Cookie operating HttpServletResponse provide only a addCookie (Cookie cookie), so you want to modify Cookie Cookie can only use the same name to overwrite the original Cookie. If you want to delete a Cookie, Cookie only need to create the same name, and maxAge set to 0, and you can overwrite the original Cookie.

The new Cookie, in addition to value, attributes other than maxAge, such as name, path, domain must reach modify or delete an effect consistent with the original order. Otherwise, the browser will be treated as two different Cookie will not be covered.

It is noteworthy that, when the client read Cookie from, including other attributes including maxAge is unreadable, it will not be submitted. The browser will only be submitted when submitting Cookie name and value attributes, maxAge property browser only be used to determine whether the Cookie expires, rather than using the server to judge.

image

We were unable to determine whether the cookie has expired, maxAge just a read-only attribute, value is always -1 on the server side by cookie.getMaxAge (). When the cookie expires, the browser will automatically interact with the background when screening expired cookie, the cookie expired will not be carried.

Cookie domain name

Cookie is not cross-domain, privacy, security mechanism prevents the site from illegally obtaining Cookie other sites.

Normally, two second-level domain of a domain is the same cookies can not be used interchangeably, and such test1.mcrwayfun.com test2.mcrwayfun.com, because the two are not identical domains. If you want to mcrwayfun.com second-level domain name can use the Cookie, Cookie parameters need to set the domain is .mcrwayfun.com , so use test1.mcrwayfun.com and test2.mcrwayfun.com will be able to access the same cookie

Level domain, also known as top-level domain, generally by the string + suffix. The domain name has a familiar baidu.com, qq.com. com, cn, net and so is a common suffix.
Secondary domain is derived in a domain, such as domain names have a mcrfun.com , the blog.mcrfun.com and www.mcrfun.com are derived out of the secondary domain.

Cookie Path

path attribute decided to allow access to the path of Cookie. For example, set to "/" indicates that all paths are allowed to use the Cookie



Author: mcrwayfun
link: https: //www.jianshu.com/p/6fc9cea6daa2
Source: Jane books
are copyrighted by the author. Commercial reprint please contact the author authorized, non-commercial reprint please indicate the source.

Published 214 original articles · won praise 292 · Views 3.32 million +

Guess you like

Origin blog.csdn.net/chelen_jak/article/details/104794391