4

Is there a way to make cookies secure and/or http-only without using response.setHeader like this:

response.setHeader("Set-Cookies", 
   "name1=value2; Path=/path; Secure; HttpOnly," +
   "name2=value2; Expires=Sun, 03-Jun-2012 23:00:56 GMT; Path=/, etc.");

But using some built-in functionality?

P.S. I'm not talking about session cookies, but custom cookies an application uses.

Eugene Retunsky
  • 13,009
  • 4
  • 52
  • 55
  • If you use Servlet 3.0, check [this question][1]. [1]: http://stackoverflow.com/questions/3033349/httponly-session-cookie-servlet-3-0-e-g-glassfish-v3 – Luciano May 05 '12 at 01:29
  • This is different. I can setup secure session cookies. I'd like to make other cookies secure. – Eugene Retunsky May 05 '12 at 02:50

1 Answers1

4

Check the javadoc. There's a HttpServletResponse#addCookie(). Your particular example can be solved as follows:

Cookie name1 = new Cookie("name1", "value1");
name1.setPath("/path");
name1.setSecure(true);
name1.setHttpOnly(true);

Cookie name2 = new Cookie("name2", "value2");
name2.setPath("/");
name2.setMaxAge(secondsUntil3Jun2012);

response.addCookie(name1);
response.addCookie(name2);
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555