Delete a cookie in Java
Cookie [] cookies = request. getcookies ();
// Cookies are cleared if they are not empty.
If (cookies! = NULL)
...{
String value = Cookies [0]. getname ();
// Search for the user name
If (value. Equals ("username "))
...{
Cookies [0]. setmaxage (0 );
Response. addcookie (Cookies [I]);
}
}
How to read and write cookies in Java
// Write cookie
Cookie namecookie = new cookie ("name", name );
Cookie passwordcookie = new cookie ("password", password );
Cookie optioncookie = new cookie ("option", "1 ");
// Lifecycle
Namecookie. setmaxage (60*60*24*365 );
Passwordcookie. setmaxage (60*60*24*365 );
Optioncookie. setmaxage (60*60*24*365 );
Response. addcookie (namecookie );
Response. addcookie (passwordcookie );
Response. addcookie (optioncookie );
// Read cookie
Cookie [] cookies = request. getcookies ();
If (cookies! = NULL)
...{
String name = "";
String Password = "";
String option = "";
For (INT I = 0; I <cookies. length; I ++)
...{
Cookie c = Cookies [I];
If (C. getname (). inclusignorecase ("name "))
...{
Name = C. getvalue ();
}
Else if (C. getname (). inclusignorecase ("password "))
...{
Password = C. getvalue ();
}
Else if (C. getname (). inclusignorecase ("option "))
...{
Option = C. getvalue ();
}
}
}
Setmaxage (parameter): If the parameter is set to negative, the cookie is cleared when the browser is closed. If the parameter is set to 0, the table deletes the cookie. If the parameter is set to positive, the number of seconds that the table cookie exists.
Httpservletresponse. addcookie (parameter 1, parameter 2): Write the created cookie to the user's computer. Parameter 1 indicates the cookie name, and parameter 2 indicates the cookie value.
Use httpservletrequest. the getcookies () method can read the cookie list from the corresponding user, put it in the cookie type array, and use the getname () and getvalue () of each cookie in the array () to obtain the names and values of each cookie.