Java operation of Cookies

Source: Internet
Author: User

Write cookies:

Cookie cookie = new Cookie (constants.cookie4sessionname, Session.getsessionid ()); Cookie.setpath ("/");//Set Root path Cookie.setdomain (". baidu.com");//set access domain, primary domain and subdomain can share cookies or set cross-domain cookie Cookie.setmax        Age (Constants.defaultcookiesessionage * 24 * 3600); Response.addcookie (cookie);

Note: To delete a cookie, set MaxAge to 0, and specify path and domain (if not default, the path and sub-path of the default path is the Write cookie, the default domain is the full name), the modification is similar, there is no explicit modification and deletion, The essence is coverage and timeout invalidation.

Cookie.setpath ("/");        Cookie.setdomain (". baidu.com"); Cookie.setmaxage (0);

Read cookies:

public static String GetSessionID (HttpServletRequest request) {cookie[] cookies = request.getcookies ();        if (null = = Cookie | | cookies.length = = 0) return null; for (Cookie cookie:cookies) {if (Constants.cookie4SessionName.equals (Cookie.getname ())) {return            Cookie.getvalue ();    }} return null; }

Of course, the Cookie can be encapsulated into a cookiemap using more convenient, map<string, cookie> cookiemap ...

A bit of a headache is that when the cookie is obtained, if the root domain and the whole domain are set a key value pair, the domain information is not available, you can first delete the unwanted domain cookie.


Java operation of Cookies

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.