Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

From a servlet, how do I set a Cookie that never expires?

From a servlet, how can I set a cookie that will never expire?

I have tried doing it like this:

Cookie cookie = new Cookie("xyz","");
cookie.setMaxAge(-1);

But when I do it this way, it expires as soon as the user closes the browser.

like image 337
Jitendra Chauhan Avatar asked Apr 11 '15 04:04

Jitendra Chauhan


People also ask

Can you set a cookie to never expire?

Disclaimer: All the cookies expire as per the cookie specification. So, there is no block of code you can write in JavaScript to set up a cookie that never expires. It is just impossible and is a fact.

How do I set my cookie lifetime?

You can extend the life of a cookie beyond the current browser session by setting an expiration date and saving the expiry date within the cookie. This can be done by setting the 'expires' attribute to a date and time.

How cookies can be handled using servlets?

To make a cookie, create an object of Cookie class and pass a name and its value. To add cookie in response, use addCookie(Cookie) method of HttpServletResponse interface. To fetch the cookie, getCookies() method of Request Interface is used.


1 Answers

If you call setMaxAge() with a negative number (or don't call it at all), the cookie will expire at the end of the user's browser session. From the documentation:

A negative value means that the cookie is not stored persistently and will be deleted when the Web browser exits.

The typical approach for cookies that "never" expires is to set the expiration time some far amount into the future. For example:

cookie.setMaxAge(60 * 60 * 24 * 365 * 10);

Will set the expiration time for 10 years in the future. It's highly probable that the user will clear their cookies (or probably just get a new computer) within the next 10 years, so this is effectively the same as specifying that it should never expire.

Keep in mind that cookies don't actually have a concept of a "maximum age"; the way this is actually implemented is Java adds the specified number of seconds to the server's current system time, then sends that time as the expiration time for the cookie. So, large mismatches between server time and client time can complicate things a little - the best you can do (at least, easily) is ensure your server clock is set correctly and hope the clients' clocks are set.

like image 165
Jason C Avatar answered Oct 26 '22 18:10

Jason C