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?
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.
To add cookie in response, use addCookie(Cookie) method of HttpServletResponse interface. To fetch the cookie, getCookies() method of Request Interface is used.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With