1. Set cookie
Cookie = new cookie ("key", "value ");
Cookie. setmaxage (60 );
Set the 60-second lifetime. If it is set to a negative value, it is the browser process cookie (saved in memory). If it is disabled, the browser becomes invalid.
Cookie. setpath ("/test/Test2 ");
Set the Cookie Path. If not set, it is the current path (for servlet, It is the URL-pattern path part of the servlet configured in request. getcontextpath () + web. XML)
Response. addcookie (cookie );
2. Read cookie
This method can read all cookie objects in the current path and "direct parent path". If no cookie exists, null is returned.
Cookie [] cookies = request. getcookies ();
3. delete a cookie
Cookie = new cookie ("key", null );
Cookie. setmaxage (0 );
Set 0 to delete the cookie immediately
Cookie. setpath ("/test/Test2 ");
Delete the cookie in the specified path. If this path is not set, the cookie in the current path is deleted by default.
Response. addcookie (cookie );
4. Note: assume that 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 in different paths.
B. if no cookie with the key "key" is found in the current path, all parent paths are queried, perform the delete operation upon retrieval (only one parent path cookie closest to the user can be deleted at a time)
Ff. You must specify the same path used to delete and modify the cookie when setting the cookie, and specify the path for the key name of the cookie, regardless of uppercase, lowercase, or both sizes.
Ie. When the key name is lower-case, if the current path is/test/Test2, if it cannot be found, then query/test,/test555,/test345. If it cannot be found, query /. (/Test555/test666 not query)
When key names are both case-sensitive and uppercase, if no path is specified, the current path is deleted by default and the query is not performed upwards.
C. When reading a cookie, you can only read the cookie in the direct parent path.
If the current path is/test/Test2, the key to be read is "key ". After reading the current path, you need to read/test,/test, and then read/
D. When working on Java Web projects, because the general web servers (such as Tomcat or jetty) Use context to manage different Web applications, each context has a different path,
Be especially careful when there are multiple Web applications in a server. Do not set cookie with path as/, which is easy to misoperate. (Of course, the premise is that the domain name is the same)