java 从 servlet,如何设置永不过期的 Cookie?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29574187/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
From a servlet, how do I set a Cookie that never expires?
提问by Jitendra Chauhan
From a servlet, how can I set a cookie that will never expire?
从 servlet,如何设置永不过期的 cookie?
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.
但是当我这样做时,一旦用户关闭浏览器,它就会过期。
回答by Jason C
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:
如果您setMaxAge()
使用负数调用(或根本不调用),cookie 将在用户浏览器会话结束时过期。从文档:
A negative value means that the cookie is not stored persistently and will be deleted when the Web browser exits.
负值表示 cookie 不会持久存储,将在 Web 浏览器退出时删除。
The typical approach for cookies that "never" expires is to set the expiration time some far amount into the future. For example:
“永不”过期的 cookie 的典型方法是将过期时间设置为未来一段时间。例如:
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.
将在未来设置 10 年的到期时间。用户很可能会在未来 10 年内清除他们的 cookie(或者可能只是获得一台新计算机),因此这实际上与指定它永远不会过期相同。
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.
请记住,cookie 实际上并没有“最大使用期限”的概念;实际实现的方式是 Java 将指定的秒数添加到服务器的当前系统时间,然后将该时间作为 cookie 的到期时间发送。因此,服务器时间和客户端时间之间的大不匹配会使事情变得有点复杂 - 您能做的最好的事情(至少,很容易)是确保您的服务器时钟设置正确,并希望设置客户端的时钟。
回答by raslan
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.
设置最大年龄:您使用 setMaxAge 来指定 cookie 的有效期(以秒为单位)。以下将设置 24 小时的 cookie。
cookie.setMaxAge(60*60*24);