Saturday, 23 April 2016

How do I make cookies expire after a set time period ?


If your cookie sends a user identifier that facilitates access to sensitive data, or allows changes to be made (for example, a web-based email service), then you should expire cookie after a small time period. If the user keeps using your servlet, you always have the option of resending the cookie with a longer duration.

For example, for a five minute expiration, we would do the following :
// Create a new cookie
Cookie cookie = new Cookie ("userID", "143011");
// Expire the cookie in 300 seconds = 5 minutes
cookie.setMaxTime(300);

When the cookie is sent back to the browser using HttpServletResponse.addCookie(Cookie), it will only be returned by the browser until the expiration date occurs.
If you would prefer, you can also specify a negative value for setMaxTime(int), and the cookie will expire as soon as the browser exits.

Note : However that not everyone will shutdown their browser, and it might be available for minutes, hours even days.
Finally, specifying a value to 0 will expire the cookie instantly.

No comments:

Post a Comment

Note: only a member of this blog may post a comment.