views:

79

answers:

1

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?

A: 

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.

JoseK
All this would prove is that a specific implementation of `HttpServletResponse` does something. The API doesn't define the behaviour, though, so other implementations might do something else.
skaffman
Well i've suggested the O/P try out on his server to verify the behaviour
JoseK
@JoseK - well, it would have better to suggest that he not do it at all! It is creating a potential portability issue.
Stephen C
I know about the undefined behavior in that RFC but have hoped for a better specification in the Servlet API (which is not covered by the Javadocs).
tbh