Home > Java > javaTutorial > body text

How to set HttpOnly Cookie in Java?

PHPz
Release: 2023-04-22 18:37:08
forward
1695 people have browsed it

Httponly cookie is a cookie security solution.

In browsers that support httponly cookies (IE6, FF3.0), if the "httponly" attribute is set in the cookie, the JavaScript script will not be able to read the cookie information, which can effectively prevent XSS attacks and allow the website to The application is more secure.

But J2EE4 and J2EE5 cookies do not provide a method to set the httponly attribute, so if you need to set the httponly attribute, you need to handle it yourself.

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
 
/**
 * Cookie Tools
 */
public class CookieUtil {
 
    /**
           * Set httponly cookie
     * @param  Response HTTP response
     * @param  Cookie cookie object
     * @param  Ishttponly is httponly
     */
    public static void addCookie(HttpServletResponse response, Cookie cookie, boolean isHttpOnly) {
        String name = cookie.getName();//Cookie name
        String value = cookie.getValue();//Cookie value
        int maxAge = cookie.getMaxAge();//Maximum survival time (milliseconds, 0 representative deletion, -1 represents the same as the browser session)
        String path = cookie.getPath();//path
        String domain = cookie.getDomain();//area
        boolean isSecure = cookie.getSecure();//Is there a security protocol? 
 
        StringBuilder buffer = new StringBuilder();
 
        buffer.append(name).append("=").append(value).append(";");
 
        if (maxAge == 0) {
            buffer.append("Expires=Thu Jan 01 08:00:00 CST 1970;");
        } else if (maxAge > 0) {
            buffer.append("Max-Age=").append(maxAge).append(";");
        }
 
        if (domain != null) {
            buffer.append("domain=").append(domain).append(";");
        }
 
        if (path != null) {
            buffer.append("path=").append(path).append(";");
        }
 
        if (isSecure) {
            buffer.append("secure;");
        }
 
        if (isHttpOnly) {
            buffer.append("HTTPOnly;");
        }
 
        response.addHeader("Set-Cookie", buffer.toString());
    }
 
}
Copy after login

It is worth mentioning that the cookie in Java Ee 6.0 has set httponly, so if it is compatible with a Java EE 6.0 compatible container (such as Tomcat 7), you can use cookie.sethttponly to set HTTPONLY:

cookie.setHttpOnly(true);
Copy after login

The setHttpOnly(Boolean httpOnly) method of the Java HttpCookie class is used to indicate whether the cookie can be considered HTTPOnly. If set to true, the cookie cannot be accessed by scripting engines such as JavaScript.

Syntax

public void setHttpOnly(boolean httpOnly)
Copy after login

Scope

The above method requires only one parameter:

httpOnly - true if the cookie is HTTP only, which means it Visible as part of the HTTP request.

Return

Not applicable

Example 1

import java.net.HttpCookie;  
public class JavaHttpCookieSetHttpOnlyExample1 {  
  public static void main(String[] args) {  
    HttpCookie  cookie = new HttpCookie("Student", "1");  
    // Indicate whether the cookie can be considered as HTTP Only or not.  
        cookie.setHttpOnly(true);  
    // Return true if the cookie is considered as HTTPOnly.  
System.out.println("Check whether the cookie is HTTPOnly: "+cookie.isHttpOnly());  
     }  
 }
Copy after login

Output:

Check whether the cookie is HTTPOnly: true

Example 2

import java.net.HttpCookie;  
public class JavaHttpCookieSetHttpOnlyExample2 {  
    public static void main(String[] args) {  
        HttpCookie  cookie = new HttpCookie("Student", "1");  
        // Indicate whether the cookie can be considered as HTTP Only or not.  
            cookie.setHttpOnly(false);  
        // Return false if the cookie is not considered as HTTPOnly.  
    System.out.println("Check whether the cookie is HTTPOnly: "+cookie.isHttpOnly());  
   }  
}
Copy after login

Output:

Check whether the cookie is HTTPOnly: false

Example 3

import java.net.HttpCookie;  
public class JavaHttpCookieSetHttpOnlyExample3 {  
    public static void main(String[] args) {  
        HttpCookie cookie1 = new HttpCookie("Student1", "1");  
        HttpCookie cookie2 = new HttpCookie("Student2", "2");  
        //Indicate whether the cookie can be considered as HTTP Only or not.  
        cookie1.setHttpOnly(true);  
        cookie2.setHttpOnly(false);  
        System.out.println("Check whether the first cookie is HTTPOnly:"+cookie1.isHttpOnly());  
        System.out.println("Check whether the second cookie is HTTPOnly:"+cookie2.isHttpOnly());  
       }  
    }
Copy after login

Output:

Check whether the first cookie is HTTPOnly:true
Check whether the second cookie is HTTPOnly:false

The above is the detailed content of How to set HttpOnly Cookie in Java?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!