1. Set Cookies
Copy Code code as follows:
Cookie cookie = new Cookie ("Key", "value");
Cookie.setmaxage (60);
Sets a 60-second lifetime, and if set to a negative value, the browser process cookie (saved in memory) is invalidated when the browser is closed.
Copy Code code as follows:
Cookie.setpath ("/test/test2");
Set cookie path, not set as current path (for servlet Request.getcontextpath () + web.xml The Url-pattern path portion of the servlet configured)
Copy Code code as follows:
Response.addcookie (cookie);
2. Read cookies
This method can read the current path and all the cookie objects of the direct parent path, or null if there are no cookies
Copy Code code as follows:
cookie[] cookies = request.getcookies ();
3. Delete Cookies
Copy Code code as follows:
Cookie cookie = new Cookie ("key", null);
Cookie.setmaxage (0);
Set to 0 to remove the cookie immediately
Copy Code code as follows:
Cookie.setpath ("/test/test2");
Deletes the cookie on the specified path, does not set the path, and defaults to deleting the current path cookie
Copy Code code as follows:
Response.addcookie (cookie);
4. Note: Suppose the path structure is as follows
Copy Code code as follows:
test/test2/test345/test555/test666
A. Cookies with the same key name (values can be the same or different) can exist under different paths.
B. At the time of deletion, if there is no cookie with the key "key" under the current path, query all the parent paths and retrieve the delete operation (only one with its closest parent path cookie at a time)
FF. You must specify the same path to use when setting cookies to remove the cookie, and the cookie's key name, regardless of uppercase, lowercase, or mixed size, specifies the path.
IE. When the key name is lowercase, if the current path is/TEST/TEST2, if you can not find the/test,/test555,/test345, if you can not find the query/. (/test555/test666 not query)
When a key name is mixed or uppercase, the current path is deleted by default without specifying a path and is not queried up.
C. Cookies can only be read from a direct parent path when reading cookies.
If the current path is/test/test2, the key to read is "key". After the current path is read, also read the/test,/test read/
D. When doing Java Web projects, because a typical Web server (such as Tomcat or jetty) uses the context to manage different webapplication, there is a different path for each context.
Be especially careful when you have multiple webapplication in one server, do not set path to/cookies, easy to operate incorrectly. (Of course, if the domain name is the same)