How to set session timeout dynamically in Java web applications?

后端 未结 4 2278
慢半拍i
慢半拍i 2020-11-30 23:50

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 fo

4条回答
  •  青春惊慌失措
    2020-11-30 23:57

    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:

    
    ...      
                                        
        com.example.MyHttpSessionListener
      
    
    

    (or since Servlet version 3.0 you can use @WebListener annotation instead).


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

    
    ...
      
        15 
      
    
    

提交回复
热议问题