How to read and write cookies in Java

Source: Internet
Author: User

Delete Cookies in Java cookie[] cookies=request.getcookies (); //cookies are not empty, then clearif(cookies!=NULL) {String value=cookies[0].getname (); //Find a user name    if(Value.equals ("UserName") ) {cookies[0].setmaxage (0);         Response.addcookie (Cookies[i]); }} How to read and write cookies in Java//Write a cookieCookie Namecookie =NewCookie ("name", name); Cookie Passwordcookie=NewCookie ("password"), password); Cookie Optioncookie=NewCookie ("option", "1"); //Life cycleNamecookie.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 Cookiescookie[] Cookies =request.getcookies (); if(cookies!=NULL) {String name= ""; String Password= ""; String option= "";  for(inti = 0; i < cookies.length; i++) {Cookie C=Cookies[i]; if(C.getname (). Equalsignorecase ("name") ) {Name=C.getvalue (); }            Else if(C.getname (). Equalsignorecase ("Password") ) {Password=C.getvalue (); }            Else if(C.getname (). Equalsignorecase ("option")) ) {option=C.getvalue (); }}} setmaxage (parameter): A negative number means that the cookie is cleared when the browser is closed, the parameter is 0 o'clock to delete the cookie, and the parameter is positive for how many seconds the cookie exists. Httpservletresponse.addcookie (parameter 1, parameter 2): writes the created cookie to the user's computer. Parameter 1 represents the name of the cookie, and parameter 2 represents the value of the cookie. The Httpservletrequest.getcookies () method allows you to read a list of cookies from the appropriate user, placed in an array of cookie types, through the GetName () and GetValue () of each cookie in the array method to obtain the names and values of individual cookies. 

Reprint to: http://blog.csdn.net/ago52030/article/details/1834237

How to read and write cookies in Java

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.