Setting several cookies in same response

22,170

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);
Share:
22,170
Duveit
Author by

Duveit

Updated on July 09, 2022

Comments

  • Duveit
    Duveit almost 2 years

    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.

  • Duveit
    Duveit over 11 years
    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.
  • BalusC
    BalusC over 11 years
    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
    BalusC over 11 years
    To support the previous comment, please carefully read stackoverflow.com/questions/572482/… 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.
  • Duveit
    Duveit over 11 years
    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.