Setting an httponly cookie with javax.servlet 2.5

You are right, manually setting header is the right way to achive your goal.

You can also use javax.ws.rs.core.NewCookie or any other class with useful toString method to print cookie to a header to make things more simple.

public static String getHttpOnlyCookieHeader(Cookie cookie) {

    NewCookie newCookie = new NewCookie(cookie.getName(), cookie.getValue(), 
            cookie.getPath(), cookie.getDomain(), cookie.getVersion(), 
            cookie.getComment(), cookie.getMaxAge(), cookie.getSecure());

    return newCookie + "; HttpOnly";
}

And the usage:

response.setHeader("SET-COOKIE", getHttpOnlyCookieHeader(myOriginalCookie));

Leave a Comment