Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting several cookies in same response

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.

like image 696
Duveit Avatar asked Oct 24 '12 15:10

Duveit


1 Answers

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.

Cookie cookie1 = new Cookie("1","1");
cookie1.setMaxAge(1209600);
response.addCookie(cookie1);
Cookie cookie2 = new Cookie("2","2");
cookie2.setMaxAge(1209600);
response.addCookie(cookie2);
like image 92
BalusC Avatar answered Sep 20 '22 14:09

BalusC