以编程方式确定 Java 会话超时
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1915084/
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
Programmatically Determine Java Session Timeout
提问by David
Is there any way for a java servlet/jsp to determine the webserver's session timeout (in seconds, minutes, etc...)? I tried looking in the HttpSession and System API, but didn't see any property for determining the webserver's session timeout. I know that this value is set in web.xml, but I am designing a java library which needs to determine this through code.
java servlet/jsp 有没有办法确定网络服务器的会话超时(以秒、分钟等为单位)?我尝试查看 HttpSession 和 System API,但没有看到任何用于确定网络服务器会话超时的属性。我知道这个值是在 web.xml 中设置的,但是我正在设计一个需要通过代码来确定它的 java 库。
Note: I am designing for a generic webserver and cannot rely on vendor specific extensions.
注意:我正在设计一个通用的网络服务器,不能依赖供应商特定的扩展。
采纳答案by David
HttpSession.getMaxInactiveIntervalprovides this value
HttpSession.getMaxInactiveInterval提供这个值
int getMaxInactiveInterval()
Returns the maximum time interval, in seconds, that the servlet container will keep this session open between client accesses. After this interval, the servlet container will invalidate the session. The maximum time interval can be set with the setMaxInactiveInterval method.
A return value of zero or less indicates that the session will never timeout.
Returns: an integer specifying the number of seconds this session remains open between client requests
int getMaxInactiveInterval()
返回 servlet 容器将在客户端访问之间保持此会话打开的最大时间间隔(以秒为单位)。在此时间间隔之后,servlet 容器将使会话无效。可以使用 setMaxInactiveInterval 方法设置最大时间间隔。
零或更少的返回值表示会话永远不会超时。
返回: 一个整数,指定此会话在客户端请求之间保持打开的秒数
回答by BalusC
In a Servlet use:
在 Servlet 中使用:
int timeoutInSeconds = request.getSession().getMaxInactiveInterval();
In a JSP use:
在 JSP 中使用:
<p>Timeout in seconds: ${pageContext.session.maxInactiveInterval}</p>
回答by ZZ Coder
The session's timeout is determined by idle time so there is no way to know when it will timeout.
会话的超时时间由空闲时间决定,因此无法知道何时会超时。
However, you can calculate the next possible timeout assuming session is not being accessed,
但是,假设没有访问会话,您可以计算下一个可能的超时时间,
Date expiry = new Date(session.getLastAccessedTime() + session.getMaxInactiveInterval()*1000);
回答by user3490522
This is the code to get the time out value:
这是获取超时值的代码:
<%= session.getMaxInactiveInterval() %>
回答by stimpie
You can call getMaxInactiveIntervalon your session object.
您可以在会话对象上调用getMaxInactiveInterval。

