【英文】用JavaWeb实现Cookie读写

Preface

Implement Cookie read and write using JavaWeb

Sending Cookies to the Client

  • 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();
1
2
3
4
5
6
7
8
for (Cookie cookie : cookies) {
String name = cookie.getName();
if (name.equals("")) {
String value = cookie.getValue();
System.out.println(name + " : " + value);
break;
}
}
  • Returns a String
1
cookie.getName();
  • Returns a String
1
cookie.getValue();

<value>: Modified value of the Cookie

1
cookie.setValue("<value>");

<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>);
1
cookie.setPath("/");
1
2
cookie.setDomain("jd.com");
cookie.setDomain("www.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.

Completion

References

Bilibili - Black Horse Programmer