Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you update an existing cookie in JSP?

Tags:

java

jsp

cookies

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.

like image 698
James Sumners Avatar asked Feb 23 '11 15:02

James Sumners


People also ask

How do I change the value of a cookie in Java?

How to update a cookie. String name = "Cookie name" ; String value = "New value" ; Cookie cookie = new Cookie(name, value);

How can I set a cookie and delete a cookie from within a JSP page?

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.


2 Answers

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.

like image 74
James Sumners Avatar answered Oct 25 '22 16:10

James Sumners


Just set the path, ex:

cookie.setPath("/");

This should overwrite the old cookie value.

like image 27
Friendly Avatar answered Oct 25 '22 18:10

Friendly