I just announced the new Spring 5 modules in REST With Spring:
This tutorial will show how to set up session timeout in a Servlet based web application.
2. Global Session Timeout in the web.xml
The timeout of all Http Sessions can be configured in the web.xml of the web application:
<?xml version="1.0" encoding="UTF-8"?> <web-app ...> ... <session-config> <session-timeout>10</session-timeout> </session-config> </web-app>
Note that the value of the timeout is set in minutes, not in seconds.
An interesting sidenode is that, in a Servlet 3.0 environment where annotations may be used instead of the XML deployment descriptor, there is no way to programmatically set the global session timeout. Programmatic configuration for session timeout does have an open issue on the Servlet Spec JIRA – but the issue has not yet been scheduled.
3. Programmatic Timeout per individual Session
The timeout of the current session only can be specified programmatically via the API of the javax.servlet.http.HttpSession:
HttpSession session = request.getSession(); session.setMaxInactiveInterval(10*60);
As opposed to the <session-timeout> element which had a value in minutes, the setMaxInactiveInterval method accepts a value in seconds.
4. Tomcat Session Timeout
All Tomcat servers provide a default web.xml file that can be configured globally for the entire web server – this is located in:
This default deployment descriptor does configure a <session-timeout> with to a value of 30 minutes.
Individual deployed applications, providing their own timeout values in their own web.xml descriptors will have priority over and will override this global web.xml configuration.
Note that the same is possible in Jetty as well: the file is located in:
This tutorial discussed the practical aspects of how to configure the timeout of the HTTP Session in a Servlet Java application. We also illustrated how this can be set at the web server level, both in Tomcat as well as in Jetty.
The implementation of these examples can be found in the github project – this is an Eclipse based project, so it should be easy to import and run as it is.
When the project runs locally, the homepage html can be accessed at: