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. Modify cookie
Cookie [] cookies = request. getCookies ();
If (cookies. length> 1 ){
For (int I = 0; I <cookies. length; I ++ ){
If (cookies [I]. getName (). equals ("key ")){
String oldValue = cookies [I]. getValue ();
String newValue = "newValue ";
Cookies [I]. setValue (newValue );
Response. addCookie (cookies [I]);
Break;
}
}
}