如何在Java Web应用程序中动态设置会话超时? [英] How to set session timeout dynamically in Java web applications?

查看:208
本文介绍了如何在Java Web应用程序中动态设置会话超时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要为用户提供一个Web界面来更改会话超时间隔。因此,Web应用程序的不同安装可以为其会话设置不同的超时,但它们的 web.xml 不能有所不同。

I need to give my user a web interface to change the session timeout interval. So, different installations of the web application would be able to have different timeouts for their sessions, but their web.xml cannot be different.

有没有办法以编程方式设置会话超时,这样我就可以使用 ServletContextListener.contextInitialized()来读取配置的时间间隔并设置应用程序启动时它?

Is there a way to set the session timeout programatically, so that I could use, say, ServletContextListener.contextInitialized() to read the configured interval and set it upon application startup?

非常感谢。

推荐答案

使用ServletContextListener,使用 HttpSessionListener 。在 sessionCreated() 方法,您可以通过编程方式设置会话超时。

Instead of using a ServletContextListener, use a HttpSessionListener. In the sessionCreated() method, you can set the session timeout programmatically.

public class MyHttpSessionListener implements HttpSessionListener{
  public void sessionCreated(HttpSessionEvent event){
    event.getSession().setMaxInactiveInterval(15*60); //in seconds
  }
  public void sessionDestroyed(HttpSessionEvent event){}
}

并且不要忘记在部署描述符中定义监听器:

And don't forget to define the listener in the deployment descriptor:

<webapp>
...
  <listeners>
    <listener-class>com.example.MyHttpSessionListener</listener-class>
  </listeners>
</webapp>

不过,我建议为每个应用程序创建不同的web.xml文件,并在那里定义会话超时:

Still, I would recommend creating different web.xml files for each application and defining the session timeout there:

<webapp>
...
  <session-config>
    <session-timeout>15</session-timeout> <!-- in minutes -->
  </session-config>
</webapp>

这篇关于如何在Java Web应用程序中动态设置会话超时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆