Cookie expiration is not working

1.8k Views Asked by At

We have an existed created cookies and they don't have any expiry date, so they are using 30 minutes default time to expire. I just wanted to make them expire in 2 minutes like below with set max age.

Cookie sessionCookie = new Cookie("sessioncookie", "345rfhthjii");
sessionCookie.setPath("/");
sessionCookie.setSecure(true);
sessionCookie.setMaxAge(120);
response.addCookie(sessionCookie);

The above code does not work, So i went through the other posts which are related to this session expiration but every solution tells about date/time which needs to set in jsp pages.

Can't we do any thing in the servlet itself?

3

There are 3 best solutions below

0
On

I know this was a few years ago, but I have been searching the min time one can set to Max-age, and on my trials the browser does not store anything less than 5 minutes, maybe that's the minimum.

0
On

I tested your code in Firefox. The way you are storing cookies are correct and you are right. When a cookie is expired Firefox doesn't delete it immediately.

Test cookie

As you can see test cookie is expired but exists in cookie list in Firefox yet. But you can not access this cookie by Javascript and also browser doesn't send this cookie to server. You can test it by this command in servlet:

Cookie[] cookies = req.getCookies();

Apparently this is browser policy to update cookie list.

0
On

The method setMaxAge(int) sets the expiration of the cookie in seconds, so your code:

sessionCookie.setMaxAge(120);

Should correctly create a cookie that will expire after 2 minutes.

I would check to make sure that your are clearing previous cookies, because your syntax is correct and you should be experiencing the intended behavior you described.