1. Set Cookie
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 ).
Instance
| The code is as follows: |
Copy code |
|
Response. addCookie (cookie );
Public static void setCookie (HttpServletResponse response, String name, String value, String path ){
If (logger. isDebugEnabled ()){
Logger. debug ("Setting cookie '" name "'on path'" path "'");
}
Cookie cookie = new Cookie (name, value );
Cookie. setSecure (false );
Cookie. setPath (path );
Cookie. setMaxAge (Constants. COOKIE_INVALID_TIME );
Response. addCookie (cookie );
// Logger.info ("setCookie completed ...... ");
} |
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
| The code is as follows: |
Copy code |
|
Cookie cookie = new Cookie ("key", null );
Cookie. setMaxAge (0 ); |
Instance
| The code is as follows: |
Copy code |
|
Public static void clearCookie (HttpServletRequest request, HttpServletResponse response, String path ){
Cookie [] cookies = request. getCookies ();
Try {
For (int I = 0; I <cookies. length; I ){
// System. out. println (cookies [I]. getName () ":" cookies [I]. getValue ());
Cookie cookie = new Cookie (cookies [I]. getName (), null );
Cookie. setMaxAge (0 );
Cookie. setPath (path); // enter the cookie name based on the path you created.
Response. addCookie (cookie );
}
} Catch (Exception ex ){
System. out. println ("An error occurred while deleting Cookies! ");
}
} |
Set 0 to delete the Cookie immediately;
| The code is as follows: |
Copy code |
|
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;
| The code is as follows: |
Copy code |
|
Response. addCookie (cookie ); |
Cookie call operation?
// Call
| The code is as follows: |
Copy code |
|
String cookiename = "vbo ";
String cookievalue = "cb ";
String path = "/";
SetCookie (response, cookiename, cookievalue, path );
ClearCookie (request, response, path );// |