Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set session timeout dynamically in Java web applications?

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.

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?

like image 429
Jonathas Carrijo Avatar asked Jun 02 '10 19:06

Jonathas Carrijo


People also ask

How many ways are there to configure session timeout in your application?

There are two ways to set session timeout for a Java web application: using XML or Java code.

What is session timeout in web application?

Session timeout represents the event occuring when a user does not perform any action on a web site during an interval (defined by a web server). The event, on the server side, changes the status of the user session to 'invalid' (ie.

How does session timeout work in Tomcat?

The number in session-timeout tag is in minutes. To make it unlimited or no time out in Tomcat, simply set the number to -1 and restart your Tomcat.


2 Answers

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> 
like image 178
Michael Avatar answered Sep 23 '22 02:09

Michael


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 standard web.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.

like image 33
Pascal Thivent Avatar answered Sep 26 '22 02:09

Pascal Thivent