1. Set Cookies
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.
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)
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
cookie[] cookies = request.getcookies ();
3. Delete Cookies
Cookie cookie = new Cookie ("key", null);
Cookie.setmaxage (0);
Set to 0 to remove the cookie immediately
Cookie.setpath ("/test/test2");
Deletes the cookie on the specified path, does not set the path, and defaults to deleting the current path cookie
Response.addcookie (cookie);
4. Note: Suppose the path structure is 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 Web application, there is a different path for each context.
Be especially careful when you have multiple Web application in one server, do not set path to/cookies, easy to operate incorrectly. (Of course, if the domain name is the same)