Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is calling HttpServletResponse.addCookie() with the same cookie name safe?

Tags:

java

servlets

Is calling

HttpServletResponse.addCookie();

(from servlet-api-2.5) multiple times using a cookie with the same name safe?

Safe in the sense of that there is a deterministic behavior, e.g. the subsequent calls will be ignored (the first wins) or the subsequent calls will always replace the cookie or something like that?

Example:

HttpServletResponse response = ...;
response.addCookie(new Cookie("foo", "bar"));
response.addCookie(new Cookie("foo", "42"));

Which value will be transferred to and stored by the browser?

like image 717
tbk Avatar asked Jul 07 '10 08:07

tbk


People also ask

How can a cookie be added to an HTTP response?

To add a new cookie, use HttpServletResponse. addCookie(Cookie). The Cookie is pretty much a key value pair taking a name and value as strings on construction.

Which method of HttpServletResponse interface add cookies to the HTTP response?

To add cookie in response, use addCookie(Cookie) method of HttpServletResponse interface. To fetch the cookie, getCookies() method of Request Interface is used.

How do you destroy cookies in Java?

If you want to delete a cookie you have to create a cookie that have the same name with the cookie that you want to delete and set the value to an empty string. You also need to set the max age of the cookie to 0 . And then add this cookie to the servlet's response object.


2 Answers

Updated answer - as the comments from @skaffman and @Stephen C show this is not ideal practice.

The RFC Spec at http://www.ietf.org/rfc/rfc2109.txt states

The NAME=VALUE attribute-value pair must come first in each cookie. If an attribute appears more than once in a cookie, the behavior is undefined.

On Tomcat server, the behaviour is the actual headers sent to the browser:

Set-Cookie: foo=bar
Set-Cookie: foo=42

Here foo gets overwritten. Reading the cookie later gives you 42.

like image 77
JoseK Avatar answered Oct 27 '22 01:10

JoseK


Additional comment - note that setting different sub-domains on cookies with the same name in the same response changes the behavior. I just tested saving cookies with the same name but different sub-domains on latest versions of java 1.6/firefox/safari/chrome on my mac, and it behaved as expected, saving both cookies. I understand this behavior is not guaranteed by the spec, but just sayin' it may be helpful to be aware of it.

like image 37
johnkaplantech Avatar answered Oct 26 '22 23:10

johnkaplantech