【英文】用JavaWeb实现Cookie读写
Preface
Implement Cookie read and write using JavaWeb
Sending Cookies to the Client
Creating a Cookie Object
- Cookies are composed of key-value pairs
<key>
: Key, the name of the Cookie, once specified, cannot be modified<value>
: Value, the value that the Cookie needs to save
1 | Cookie cookie = new Cookie("<key>", "<value>"); |
If the expiration date of the Cookie is not set, it will be destroyed by default after closing the browser.
Writing Cookies to the Client
- Cookies do not support Chinese characters
- Solution: Convert to data in other encoding formats
resp
: Response object
1 | resp.addCookie(cookie); |
Receiving Cookies Sent by the Client
Reading Cookies
- The result of reading is an array of Cookies
req
: Request object
1 | Cookie cookies[] = req.getCookies(); |
Traversing the Cookie Array
1 | for (Cookie cookie : cookies) { |
Operations on Cookie Objects
Get the Name of the Cookie
- Returns a String
1 | cookie.getName(); |
Get the Value of the Cookie
- Returns a String
1 | cookie.getValue(); |
Set the Value of the Cookie
<value>
: Modified value of the Cookie
1 | cookie.setValue("<value>"); |
Set the Expiration Date of the Cookie
<num>
: Unit: seconds
Negative number
: Default value, the Cookie is valid until the browser is closed (stored in the browser cache)Positive number
: Set the expiration date of the Cookie (stored on the hard disk)0
: Immediately delete the Cookie with the same name
1 | cookie.setMaxAge(<num>); |
Set the Request-Effective Path of the Cookie
1 | cookie.setPath("/"); |
Set the Domain Sharing of the Cookie
1 | cookie.setDomain("jd.com"); |
Notes on Cookies
The data stored in the Cookie is saved on the client side.
The size of a single Cookie cannot exceed 4kb.
A domain can write up to 20 Cookies to a client.
Cookies can only store information with low security requirements. Passwords and other sensitive information cannot be directly saved in Cookies.
Different browsers read different Cookies.