2021-03-06-cookie summary

origin

  • http is stateless (cannot recognize that you have been here)
  • How to ensure that the client data is consistent with the server data for a long time (shopping cart)
  • The session state allows the client to establish contact with the server
  • Two session mechanisms in Servlet: cookie, session

classification

  • Session cookie
没有用setMax设定Cookie最大生命周期
生命周期和浏览器相关
保存在内存里面
  • Persistent cookies: Use setMax to set the maximum life cycle of cookies

Realization principle

  • The WEB server adds the Set-Cookie response header field to the HTTP response information and sends the cookie information to the browser
  • The browser adds the Set-Cookie request header field to the HTTP request message to send the cookie back to the server

Precautions

  • A cookie can only contain one key-value information
  • A cookie can only identify one type of information
  • A website can send multiple cookies to a browser
  • A browser can also store cookies sent by multiple websites
  • Browsers generally only allow 300 cookies to be stored
  • Each site can store up to 20 cookies
  • The size of each cookie is limited to 4KB
  • The cookie is stored on the client and is not secure
  • The browser disables the cookie server and cannot write into it

How to use

  • Create cookie first
  • Call response.addCookie(cookie) to add cookie

Read

  • Call request.getCookies() to get the cookie array
  • Traverse the array to find the cookie by name

method

method Description
new Cookie(name,value) The constructor must be called to create a cookie
setMaxAge(int expiry) The survival time of the hard disk, in seconds, 0 means to delete immediately, and negative numbers are not stored. If this method is not set, it will be deleted after the browser is closed.
getName() Get the name of the current cookie
getValue() Get the current cookie value
setValue(String newValue) Set a new value for the current cookie
setHttpOnly(boolean httpOnly) Whether js can access the cookie, true is not accessible

Guess you like

Origin blog.csdn.net/qq_41270550/article/details/113855226