Client session technology-Cookie

Posted Jun 26, 20202 min read

Blog description

The information involved in the article comes from the Internet collation and personal summary, which means personal learning and experience summary. If there is any infringement, please contact me to delete, thank you!

Concept

Client session technology to save data to the client

Quick Start

  1. Create Cookie object and bind data

    • new Cookie(String name, String value)
  2. Send Cookie Object

    • response.addCookie(Cookie cookie)
  3. Get cookies and get data

    • Cookie[]request.getCookies()

Implementation principle

Implementation based on response header set-cookie and request header cookie

  1. Can I send multiple cookies at once?

    • Yes
    • You can create multiple Cookie objects, use response to call multiple addCookie methods to send cookies.
  2. How long do cookies stay in the browser?

    1. By default, when the browser is closed, the cookie data is destroyed

    2. Persistent storage:

      • setMaxAge(int seconds)

        1. Positive number:Write Cookie data to a file on the hard disk. Persistent storage. And specify the cookie survival time, after the time expires, the cookie file automatically expires
        2. Negative number:default value
        3. Zero:delete cookie information
  3. Can cookies be stored in Chinese?

    • Before tomcat 8, cookies cannot directly store Chinese data.

      • Need to transcode Chinese data-generally use URL encoding(%E3)
    • After tomcat 8, cookies support Chinese data. Special characters are still not supported, it is recommended to use URL encoding storage, URL decoding analysis

  4. Cookie sharing problem?

    1. Assuming that multiple web projects are deployed in a tomcat server, can cookies be shared among these web projects?

      • By default, cookies cannot be shared
        • setPath(String path):Set the scope of cookie acquisition. By default, set the current virtual directory
        • If you want to share, you can set the path to "/"
    2. The problem of cookie sharing between different tomcat servers?

      • setDomain(String path):If the first-level domain name is set the same, cookies can be shared among multiple servers
      • setDomain(".baidu.com"), then cookies in tieba.baidu.com and news.baidu.com can be shared

Features and functions of cookies

  1. Cookies store data in the client browser
  2. The browser has a limit on the size of a single cookie(4kb) and a limit on the total number of cookies under the same domain name(20)
  • Function:

    1. Cookies are generally used to deposit a small amount of less sensitive data
    2. Without logging in, complete the server's identification of the client

thank

Dark Horse Programmer

Universal Network

And hardworking self