简体   繁体   English

以编程方式确定Java会话超时

[英]Programmatically Determine Java Session Timeout

Is there any way for a java servlet/jsp to determine the webserver's session timeout (in seconds, minutes, etc...)? 有没有办法让java servlet / jsp确定webserver的会话超时(以秒,分钟等为单位......)? I tried looking in the HttpSession and System API, but didn't see any property for determining the webserver's session timeout. 我尝试查看HttpSession和System API,但没有看到任何用于确定Web服务器会话超时的属性。 I know that this value is set in web.xml, but I am designing a java library which needs to determine this through code. 我知道这个值是在web.xml中设置的,但我正在设计一个需要通过代码来确定这个值的java库。

Note: I am designing for a generic webserver and cannot rely on vendor specific extensions. 注意:我正在设计通用的Web服务器,不能依赖供应商特定的扩展。

HttpSession.getMaxInactiveInterval provides this value HttpSession.getMaxInactiveInterval提供此值

int getMaxInactiveInterval() int getMaxInactiveInterval()

Returns the maximum time interval, in seconds, that the servlet container will keep this session open between client accesses. 返回servlet容器在客户端访问之间保持此会话打开的最长时间间隔(以秒为单位)。 After this interval, the servlet container will invalidate the session. 在此间隔之后,servlet容器将使会话无效。 The maximum time interval can be set with the setMaxInactiveInterval method. 可以使用setMaxInactiveInterval方法设置最大时间间隔。

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 返回:一个整数,指定此会话在客户端请求之间保持打开的秒数

In a Servlet use: 在Servlet中使用:

int timeoutInSeconds = request.getSession().getMaxInactiveInterval();

In a JSP use: 在JSP中使用:

<p>Timeout in seconds: ${pageContext.session.maxInactiveInterval}</p>

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);

这是获取超时值的代码:

<%= session.getMaxInactiveInterval() %>

您可以在会话对象上调用getMaxInactiveInterval

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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