9

I need to create several persistent cookies in one response.

Doing it like

response.addCookie(new Cookie("1","1"));
response.addCookie(new Cookie("2","2"));

would create a response with 2 "Set-Cookie" headers. But they wouldn't be persistent. I need "expires" date for that.

expires=Wed, 07-Nov-2012 14:52:08 GMT

Seeing how javax.servlet.http.Cookie doesn't support "expires", I've previously used

String cookieString="cookieName=content;Path=/;expires=Wed, 07-Nov-2012 14:52:08 GMT;"
response.setHeader("Set-Cookie", cookieString);

Which works like a charm, but using response.setHeader("Set-Cookie",newCookie) a second time, would overwrite the first one.

So, the question is if there any way to add several identical named headers to the response? Or if there is any other correct way of doing this?

I've seen suggestions using comma separated cookies, but my experience is that only the first cookie gets read by the browser.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Duveit
  • 169
  • 2
  • 2
  • 12

1 Answers1

22

You need addHeader() instead of setHeader(). The former adds a header while the latter sets (and thus overrides any old one) a header.

response.addHeader("Set-Cookie", cookieString1);
response.addHeader("Set-Cookie", cookieString2);

The proper way, however, is to use setMaxAge() method of the Cookie class (which takes the expire time in seconds) and use addCookie() the usual way.

public static final int TWO_WEEKS_IN_SECONDS = (int) TimeUnit.DAYS.toSeconds(14);

// ...

Cookie cookie1 = new Cookie("1","1");
cookie1.setMaxAge(TWO_WEEKS_IN_SECONDS);
response.addCookie(cookie1);

Cookie cookie2 = new Cookie("2","2");
cookie2.setMaxAge(TWO_WEEKS_IN_SECONDS);
response.addCookie(cookie2);
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • 1
    Ah duh, overlooked that method apparantly, thanks for pointing it out! And cookie.setMaxAge will use maxAge and not expires in the response header, which doesn't work with IE. Basically I've found the Cookie class useless. – Duveit Oct 24 '12 at 16:10
  • You're welcome. The latter statement is only true if you use special characters in cookies for some reason. It by default definitely sets the expires attribute. – BalusC Oct 24 '12 at 16:16
  • To support the previous comment, please carefully read http://stackoverflow.com/questions/572482/why-do-cookie-values-with-whitespace-arrive-at-the-client-side-with-quotes/7233959#7233959 to understand the IE-related problem better. Summarized: don't use URL-special characters in cookie name/value, else you've got to escape/encode them somehow. If you hacked it around by setting the very same values by explicitly setting the header yourself, it would still be severily broken. – BalusC Oct 24 '12 at 16:33
  • It's being urlencoded, but might not have been when I tested out Cookie.setMaxAge(). I reckon I'll stick with setting headers as I know it works and I like having explicit control, but thanks for link. – Duveit Oct 24 '12 at 17:23