How to set session timeout dynamically in Java web applications?
Is there a way to set the session timeout programatically
There are basically three ways to set the session timeout value:
- by using the
session-timeout
in the standardweb.xml
file ~or~ - in the absence of this element, by getting the server's default
session-timeout
value (and thus configuring it at the server level) ~or~ - programmatically by using the
HttpSession. setMaxInactiveInterval(int seconds)
method in your Servlet or JSP.
But note that the later option sets the timeout value for the current session, this is not a global setting.
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>
...
<listener>
<listener-class>com.example.MyHttpSessionListener</listener-class>
</listener>
</webapp>
(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:
<webapp>
...
<session-config>
<session-timeout>15</session-timeout> <!-- in minutes -->
</session-config>
</webapp>
As another anwsers told, you can change in a Session Listener. But you can change it directly in your servlet, for example.
getRequest().getSession().setMaxInactiveInterval(123);