Last Updated on 28 June 2019   |   Print Email
By default, a servlet container (i.e. Java web server) defines the global value of session timeout for all Java web applications – e.g. the default session timeout in Tomcat is 30 minutes. And you can override the default timeout value for an individual web application on the server.There are two ways to set session timeout for a Java web application: using XML or Java code.
1. Set session timeout in web.xml file
Open the web.xml file of your web application (under WEB-INFdirectory), and specify the session timeout like this:
This sets the timeout to 15 minutes.If your web application doesn’t have the web.xml file, you need to create one in the WEB-INF directory. Here’s the full code of the web.xml file with complete XML namespaces – for your reference:
You need to restart the web application for the new session timeout takes effect.Watch the video:
2. Set session timeout using Java code
Since Java Servlet 4.0, you can programmatically set session time out for a web application by using the setSessionTimeout() method of the ServletContext interface, before the servlet context is initialized. That means you can only set session timeout in a ServletContextListener like this:
package net.codejava;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
@WebListener
public class MyWebListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
ServletContextListener.super.contextInitialized(sce);
sce.getServletContext().setSessionTimeout(45); // session timeout in minutes
}
}
This sets the session timeout for the web application to 45 minutes – and it overrides the setting in the web.xml file.You can set timeout for a specific user’s session by using the setMaxInactiveInterval() method of the HttpSession interface. For example:
Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.
Comments