I have a cookie, myCookie
, that contains a hash value. This cookie is set to expire in one year and has a path of '/'. I need to update this cookie with a new hash value. When my JSP script is loaded I retrieve the cookie like so:
Cookie[] cookies = request.getCookies();
Cookie myCookie = null;
for (int i = 0; i < cookies.length; i += 1) {
if (cookies[i].getName().equals("myCookie")) {
myCookie = cookies[i];
break;
}
}
After determining that the value of the cookie needs to be updated, I do the following to update it:
myCookie.setValue("my new value");
response.addCookie(myCookie);
Examining the results, I now have two instances of myCookie
: the original version with the correct expiration date and path, and the old, invalid, value; and a new cookie named "myCookie" that expires at the end of the session, with the correct value, and a path of the JSP document.
If I do:
myCookie.setValue("my new value");
myCookie.setPath(myCookie.getPath());
myCookie.setMaxAge(myCookie.getMaxAge());
response.addCookies(myCookie);
The same thing happens. I get two cookies with the same name and different properties.
Does a Cookie object not retain the properties from when it was retrieved? How can I update this cookie?
Note: I do not want to modify the path or the expiration date. I only want to update the value of the already set cookie.
How to update a cookie. String name = "Cookie name" ; String value = "New value" ; Cookie cookie = new Cookie(name, value);
Deleting a Cookie using JSP First, by calling the setMaxAge() method of Cookie class and passing it a zero(0) in its parameters, which sets the cookie age to zero seconds. Next, by calling addCookie() method of response object deletes the cookie from the browser's memory, as shown below.
Per section 3.3.4 of RFC 2965, the user agent does not include the expiration information in the cookie header that is sent to the server. Therefore, there is no way to update an existing cookie's value while retaining the expiration date that was initially set based solely on the information associated with the cookie.
So the answer to this question is: you can't do that.
Just set the path, ex:
cookie.setPath("/");
This should overwrite the old cookie value.
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