How to read and write cookies in Java

Source: Internet
Author: User

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.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.