Create a cookie
Java code
- New a cookie object with key-value pairs as arguments
- Cookie cookie = New Cookie ("key", "value");
- Set cookie maximum time to live, in seconds, negative if browser process, close browser cookie disappears
- Cookie.setmaxage (60); //One minute
- Add a cookie to the response to make it effective
- Response.addcookie (cookie);
Reading a cookie, reading a cookie only gets all the cookies from the request, and then iterates over it. Although the cookie is also a key-value pair, it does not seem like a map to get the value by key.
Java code
- Get a cookie from request, get a cookie array
- cookie[] cookies = request.getcookies ();
- And then iterate over the
- if (cookie = null && cookies.length > 0) { //If no cookie has been set, returns null
- For (Cookie cookie:cookies) {...}
- }
To delete a cookie and delete a cookie, simply set the lifetime of the cookie to 0
Java code
- cookie[] cookies = request.getcookies ();
- if (cookie = null && cookies.length > 0) {
- For (Cookie cookie:cookies) {
- String name = Cookie.getname ();
- //Find the cookie that needs to be deleted
- if (Name.compareto ("key") = = 0) {
- //Set lifetime to 0
- Cookie.setmaxage (0);
- //Set back to response in effect
- Response.addcookie (cookie);
- }
- }
- }
Modify the cookie, modify the cookie and delete the same steps, first find the cookie that needs to be deleted, then set its new value, and then set back to response
Java code
- cookie[] cookies = request.getcookies ();
- if (cookie = null && cookies.length >) {
- For (Cookie cookie:cookies) {
- if (Cookie.getName.compareTo ("key") = = 0) {
- Cookie.setvalue ("newvalue");
- Response.addcookie (cookie);
- Break ;
- }
- }
- }
Java cookie manipulation with knowledge point collation