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.
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);