Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

setMaxAge(0) doesnt delete cookie?

 
Maulin Vasavada
Ranch Hand
Posts: 1873
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,
I am trying to delete a cookie via a servlet when user clicks "logout" button but it doesn't work.
I have a cookie with following settings,
Cookie c = new Cookie("mycookie","maulin");
c.setPath("/");
c.setDomain(".myco.com");
when I set the cookie upon login.
On Logout button click submission I am reading all cookies where I see "mycookie" as well and then have the following code,

The above code doesn't remove the cookie from the browser BUT if I write,
temp.setMaxAge(0);
temp.setDomain(".myco.com");
temp.setPath("/");
then it works. Why? When I do temp = c[i] where c[i] has Domain and Path set then why I have to repeat the settings before I add the new cookie 'temp' to the response with max age 0?
Regards
Maulin
 
Maulin Vasavada
Ranch Hand
Posts: 1873
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
anybody has any idea?
OR my question is not clear?
Regards
Maulin
 
John Holme
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Your workaround provides the answer that works for me! That is, when I create a cookie using:

c.setMaxAge(60 * 60 * 24 * 7 * 4);
c.setDomain(".myDomain.com");
c.setPath("/myPath");
response.addCookie(c);

... it seems that the cookie is uniquely identified not just by it's name, but by it's other attributes as well (domain and path).

In order for the browser to be sure which cookie is referenced, it's necessary to duplicate the settings from the original reference:

c.setMaxAge(0);
c.setDomain(".globexplorer.com");
c.setPath("/ImageAtlas");
response.addCookie(c);

When this is done, the cookie disappears as advertised. It's curious that this behavior is not documented anywhere on the internet or in any of my numerous books. Your posting on JavaRanch was the only reference I found, and it solved my problem. Thanks!
 
John Holme
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ok, the domain and path in the second reference should match the first:

c.setMaxAge(0);
c.setDomain(".myDomain.com");
c.setPath("/myPath");
response.addCookie(c);

sorry for the sloppy cut and paste job!
jh
 
Chandika Gunawardhana
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks.
You need to set all the attributes you set when you created the cookie, to delete it.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic