简体   繁体   中英

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.

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.

Setting the maximum age : You use setMaxAge to specify how long (in seconds) the cookie should be valid. Following would set up a cookie for 24 hours.

cookie.setMaxAge(60*60*24); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM