Crud of cookie in java

Source: Internet
Author: User
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;
}
}
}

  

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.