Java Settings HttpOnly Cookies

Source: Internet
Author: User

HttpOnly cookies are a safe-line solution for cookies.

In browsers that support HttpOnly cookies (ie6+,ff3.0+), if the "HttpOnly" attribute is set in the cookie, the cookie information cannot be read through JavaScript scripts, which effectively prevents XSS attacks, Make website apps more secure.

However, the J2ee4,j2ee5 cookie does not provide a way to set the HttpOnly property, so if you need to set the HttpOnly property you need to handle it yourself.

ImportJavax.servlet.http.Cookie;ImportJavax.servlet.http.HttpServletResponse;/*** Cookie Tool class*/ Public classCookieutil {/*** Set HttpOnly Cookie *@paramResponse HTTP Response *@paramCookie Cookie Object *@paramwhether the ishttponly is HttpOnly*/     Public Static voidAddcookie (httpservletresponse response, Cookie cookie,Booleanishttponly) {String name= Cookie.getname ();//Cookie NameString value = Cookie.getvalue ();//Cookie Value        intMaxAge = Cookie.getmaxage ();//Maximum time to live (milliseconds, 0 for delete, 1 for browser session)String path = Cookie.getpath ();//PathString domain = Cookie.getdomain ();//Domain        BooleanIssecure = Cookie.getsecure ();//is the security protocol informationStringBuilder Buffer=NewStringBuilder (); Buffer.append (Name+ "=" + Value + ";"); if(MaxAge = = 0) {buffer.append ("Expires=thu Jan 08:00:00 CST 1970;"); } Else if(MaxAge > 0) {buffer.append ("Max-age=" + cookie.getmaxage () + ";"); }        if(Domain! =NULL) {buffer.append ("domain=" + domain + ";"); }        if(Path! =NULL) {buffer.append ("Path=" + path + ";"); }        if(issecure) {buffer.append ("Secure;"); }        if(ishttponly) {buffer.append ("HttpOnly;"); } Response.AddHeader ("Set-cookie", buffer.tostring ()); }}

It is worth mentioning that the cookie in Java EE 6.0 can already be set httponly, so if it is a container compatible with Java EE 6.0 (for example, Tomcat 7), you can use the Cookie.sethttponly method to set the HttpOnly directly:

Cookie.sethttponly (true);

Java Settings HttpOnly 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.