我需要为用户提供一个网页界面来更改会话超时时间间隔。因此,Web应用程序的不同安装将能够为其会话设置不同的超时时间,但它们的web.xml
不能不同。
是否有一种编程方式设置会话超时时间,以便我可以在应用程序启动时使用例如ServletContextListener.contextInitialized()
读取配置的时间间隔并进行设置?
我需要为用户提供一个网页界面来更改会话超时时间间隔。因此,Web应用程序的不同安装将能够为其会话设置不同的超时时间,但它们的web.xml
不能不同。
是否有一种编程方式设置会话超时时间,以便我可以在应用程序启动时使用例如ServletContextListener.contextInitialized()
读取配置的时间间隔并进行设置?
可以使用 HttpSessionListener
替代 ServletContextListener。
在 sessionCreated()
方法中,您可以以编程方式设置会话超时时间:
public class MyHttpSessionListener implements HttpSessionListener {
public void sessionCreated(HttpSessionEvent event){
event.getSession().setMaxInactiveInterval(15 * 60); // in seconds
}
public void sessionDestroyed(HttpSessionEvent event) {}
}
不要忘记在部署描述符中定义监听器:
<webapp>
...
<listener>
<listener-class>com.example.MyHttpSessionListener</listener-class>
</listener>
</webapp>
(或者从Servlet版本3.0开始,您可以使用@WebListener
注释代替。)
尽管如此,我建议为每个应用程序创建不同的web.xml文件,并在其中定义会话超时时间:
<webapp>
...
<session-config>
<session-timeout>15</session-timeout> <!-- in minutes -->
</session-config>
</webapp>
有没有一种方法可以通过编程方式设置会话超时时间?
基本上有三种方法可以设置会话超时值:
web.xml
文件中的session-timeout
~或~session-timeout
值(从而在服务器级别上进行配置)~或~HttpSession.setMaxInactiveInterval(int seconds)
方法进行编程。 但请注意,后一选项仅为当前会话设置超时值,这不是全局设置。
正如其他答案所说,你可以在Session监听器中进行更改。但是你也可以直接在你的servlet中进行更改,例如:
getRequest().getSession().setMaxInactiveInterval(123);
创建一个静态块(仅在第一次访问类时执行),从config.properties文件中读取超时值,并将该值设置为globalSessionTimeoutInterval变量。
现在使用该值来设置maxInactiveInterval
现在Web部分,即管理员配置页面
a. 将配置的值复制到静态变量globalSessionTimeoutInterval中。
b. 将相同的值写入config.properties文件。 (考虑服务器重新启动后,globalSessionTimeoutInterval将加载config.properties文件中存在的值)
备用.properties文件或将其存储到数据库中。选择权在您手中。
实现相同逻辑的代码:
public class MyHttpSessionListener implements HttpSessionListener
{
public static Integer globalSessionTimeoutInterval = null;
static
{
globalSessionTimeoutInterval = Read value from .properties file or database;
}
public void sessionCreated(HttpSessionEvent event)
{
event.getSession().setMaxInactiveInterval(globalSessionTimeoutInterval);
}
public void sessionDestroyed(HttpSessionEvent event) {}
}
在您的配置控制器或配置servlet中
String valueReceived = request.getParameter(timeoutValue);
if(valueReceived != null)
{
MyHttpSessionListener.globalSessionTimeoutInterval = Integer.parseInt(timeoutValue);
//Store valueReceived to config.properties file or database
}