我需要将 session 超时设置为 40 秒。我知道我们通常保持 20 分钟。但我当前的应用程序要求是将 session 超时保持在 40 秒到几秒之间。 web.xml 仅采用整数值 1,但不采用 0.6。有没有办法写这个?我们在 Apache tomcat 服务器上运行我们的 java web 应用程序。
我可以在 web.xml 中设置的最小值是 1 分钟,例如:
<session-config>
<session-timeout>1</session-timeout>
</session-config>
我可以使用 session.setMaxInactiveInterval(40); 将 session 超时设置为 40 秒;但是 session.setMaxInactiveInterval(40);仅当用户打开网站时才有效。但是一旦用户关闭网站,session.setMaxInactiveInterval 方法将不起作用,默认的 web.xml 将控制并再次将 session 超时设置为 1 分钟。
有没有办法通过一些调整在 web.xml 中以秒为单位设置 session 超时?
最佳答案
据我所知,web.xml
只允许几分钟。如果你想使用秒,你必须通过在 web.xml
中注册自定义 HttpSessionListener
(或类似的)以编程方式完成:
<listener>
<listener-class>com.sample.SessionTimeoutSetter</listener-class>
</listener>
public class SessionTimeoutSetter implements HttpSessionListener {
public void sessionCreated(HttpSessionEvent event) {
event.getSession().setMaxInactiveInterval(40);
}
public void sessionDestroyed(HttpSessionEvent event) {
// not needed
}
}
取自 servlet-api-2.4
的 HttpSession
/**
* Specifies the time, in seconds, between client requests before the
* servlet container will invalidate this session. A negative time
* indicates the session should never timeout.
*
* @param interval An integer specifying the number of seconds
*/
public void setMaxInactiveInterval(int interval);
关于java - 有没有办法通过一些调整在 web.xml 中以秒为单位设置 session 超时?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23008322/