开发者

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

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?


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜