Home » Enterprise Java » servlet » Java Servlet Session Timeout Configuration Example

About Yatin

Yatin
The author is graduated in Electronics & Telecommunication. During his studies, he has been involved with a significant number of projects ranging from programming and software engineering to telecommunications analysis. He works as a technical lead in the information technology sector where he is primarily involved with projects based on Java/J2EE technologies platform and novel UI technologies.

Java Servlet Session Timeout Configuration Example

In this tutorial, we will show you how to set up the Session Timeout in a Servlet based web application.

1. Introduction

Tomcat has a default timeout of 30 minutes but the default timeout depends on different web containers. The default session timeout in a web application can be configurable in two ways:
 
 
 
 

1.1 Session Timeout in the Deployment Descriptor

Session Timeout can be configured in the deployment descriptor (i.e. web.xml) and has virtually same effect as calling the setMaxInactiveInterval() on every session that is created. The usage is as follows:

<?xml version="1.0" encoding="UTF-8"?>
<web-app ...>
    ...
    <session-config>
        <session-timeout>10</session-timeout>
    </session-config>
</web-app>

This setting will set the timeout to 10 minutes globally to all the sessions be created by the web container. If web container does not receive any request from the client in 10 minutes time span, the web container will invalidate the session automatically.

1.1.1 But I don’t want the session to expire, how to set it?

If developers want the session to never expire, they can configure like:

<?xml version="1.0" encoding="UTF-8"?>
<web-app ...>
    ...
    <session-config>
        <session-timeout>-1</session-timeout>
    </session-config>
</web-app>

Do note, setting an infinite timeout is not recommended because once the session is created, it will never expire and will remain in the server until the server gets restarted or developer invalidates it by calling the sessionObj.invalidate() method on some user action (For e.g. Logout).

1.2 Programmatic Timeout per individual Session

If developers want to change the session timeout for any particular session then they can call the below method in that session:

HttpSession sessionObj = request.getSession(true);
sessionObj.setMaxInactiveInterval(10*60);

As opposed to the <session-timeout /> element which had a value in minutes, the setMaxInactiveInterval(timeout) method accepts a value in seconds. This setting will set the timeout to 10 minutes for an individual session. The session will be killed by the container if the client doesn’t make any request in 10 minutes time span.

In the following example, we will guide through the steps in how to programmatically configure a session timeout.

2. Java Servlet Session Timeout Configuration Example

Here is a step-by-step guide for implementing the Servlet Session Timeout in Java.

2.1 Tools Used

We are using Eclipse Kepler SR2, JDK 8 and Maven. Having said that, we have tested the code against JDK 1.7 and it works well.

2.2 Project Structure

Firstly, let’s review the final project structure, in case you are confused about where you should create the corresponding files or folder later!

Fig. 1: Application Project Structure

Fig. 1: Application Project Structure

2.3 Project Creation

This section will demonstrate on how to create a Java-based Maven project with Eclipse. In Eclipse Ide, go to File -> New -> Maven Project.

Fig. 2: Create Maven Project

Fig. 2: Create Maven Project

In the New Maven Project window, it will ask you to select project location. By default, ‘Use default workspace location’ will be selected. Just click on next button to proceed.

Fig. 3: Project Details

Fig. 3: Project Details

Select the ‘Maven Web App’ Archetype from the list of options and click next.

Fig. 4: Archetype Selection

Fig. 4: Archetype Selection

It will ask you to ‘Enter the group and the artifact id for the project’. We will input the details as shown in the below image. The version number will be by default: 0.0.1-SNAPSHOT.

Fig. 5: Archetype Parameters

Fig. 5: Archetype Parameters

Click on Finish and the creation of a maven project is completed. If you observe, it has downloaded the maven dependencies and a pom.xml file will be created. It will have the following code:

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>JavaServletSessionEx</groupId>
	<artifactId>JavaServletSessionEx</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>
</project>

We can start adding the dependencies that developers want like Servlets, Junit etc. Let’s start building the application!

3. Application Building

Below are the steps involved in developing this application.

3.1 Maven Dependencies

Here, we specify the dependencies for the Servlet API. The rest dependencies will be automatically resolved by the Maven framework and the updated file will have the following code:

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>JavaServletSessionEx</groupId>
	<artifactId>JavaServletSessionEx</artifactId>
	<packaging>war</packaging>
	<version>0.0.1-SNAPSHOT</version>
	<name>JavaServletSessionEx Maven Webapp</name>
	<url>http://maven.apache.org</url>
	<dependencies>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>3.1.0</version>
		</dependency>
	</dependencies>
	<build>
		<finalName>${project.artifactId}</finalName>
	</build>
</project>

3.2 Java Class Creation

Let’s create the required Java files. Right-click on src/main/java folder, New -> Package.

Fig. 6: Java Package Creation

Fig. 6: Java Package Creation

A new pop window will open where we will enter the package name as: com.jcg.servlet.

Fig. 7: Java Package Name (com.jcg.servlet)

Fig. 7: Java Package Name (com.jcg.servlet)

Once the package is created in the application, we will need to create a controller class. Right-click on the newly created package: New -> Class.

Fig. 8: Java Class Creation

Fig. 8: Java Class Creation

A new pop window will open and enter the file name as: TimeoutServlet. The session timeout controller class will be created inside the package: com.jcg.servlet.

Fig. 9: Java Class (TimeoutServlet.java)

Fig. 9: Java Class (TimeoutServlet.java)

3.2.1 Implementation of Timeout Servlet

This servlet will programmatically set the session timeout details. Let’s see the simple code snippet that follows this implementation.

TimeoutServlet.java

package com.jcg.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@WebServlet("/timeoutServlet")
public class TimeoutServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	/***** This Method Is Called By The Servlet Container To Process A 'POST' Request *****/
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		handleRequest(request, response);
	}

	public void handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		/***** Set Response Content Type *****/
		response.setContentType("text/html");

		/***** Print The Response *****/
		PrintWriter out = response.getWriter();
		String title = "Session Time-Out";		
		String docType = "<!DOCTYPE html>\n";
		out.println(docType 
				+ "<html>\n" + "<head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"><title>" + title + "</title></head>\n" + "<body>");

		/***** Post Parameters From The Request *****/
		String param1 = request.getParameter("username");
		if (param1 != null && !param1.equals("")) {

			int timeout = 20;
			HttpSession sessionObj = request.getSession(true);

			out.println("<div id='serlvetResponse' style='text-align: left;'>");
			out.println("<h2>Serlvet Session Timeout Example</h2>");
			out.println("<p style='color: green; font-size: large;'>Congratulations! You are an authorised login.</p>");
			out.println("<ul><li><span id=\"usernameId\">Username is?= </span>" + param1 + "</li>");
			out.println("<li><span id=\"defaultTimeOutId\">Default session timeout is?= </span>" + sessionObj.getMaxInactiveInterval() + " seconds.</li>");

			/***** Setting The Updated Session Time Out *****/
			sessionObj.setMaxInactiveInterval(timeout);
			out.println("<li><span id=\"alteredTimeOutId\">Session timeout is altered to?= </span>" + sessionObj.getMaxInactiveInterval() + " seconds.</li></ul>");

			/***** Once The Time Out Is Reached. This Line Will Automatically Refresh The Page *****/
			response.setHeader("Refresh", timeout + "; URL=timeout.jsp");
		} else {
			out.println("<p id='errMsg' style='color: red; font-size: larger; margin-left: 564px'>Please Enter a Correct Name!</p>");
			RequestDispatcher rdObj = request.getRequestDispatcher("/index.jsp");
			rdObj.include(request, response);
		}

		out.println("</body></html>");
		out.close();
	}
}

3.3 Configuring JSP Views

This example uses the index.jsp and timeout.jsp to display a welcome form and display the Session Timeout Message respectively. Let’s see the simple code snippet to implement the JSP views.

3.3.1 Configuring the Welcome Screen

index.jsp

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
	<head>
	    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	    <title>Session Timeout</title>
	    <style type="text/css">
	    	.paddingBtm {
	    		padding-bottom: 12px;
	    	}
	    </style>
	</head>
	<body>
	    <center>
	        <h2>Servlet Session Timeout Example</h2>
	        <form id="loginFormId" name="loginForm" method="post" action="timeoutServlet">
	            <div id="usernameDiv" class="paddingBtm">
	            	<span id="user">Username: </span><input type="text" name="username" />
	            </div>	           
	            <div id="loginBtn">
	            	<input id="btn" type="submit" value="Submit" />
	            </div>
	        </form>
	    </center>
	</body>
</html>

3.3.2 Configuring the Session Timeout Message

timeout.jsp

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
	<head>
	    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	    <title>Session Timeout</title>
	</head>
	<body>
	    <center>
	    	<p id='errMsg' style='color: red; font-size: larger;'>Servlet Session has Timed-Out!</p>	     
	    </center>
	</body>
</html>

4. Run the Application

As we are ready for all the changes, let us compile the project and deploy the application on the Tomcat7 server. To deploy the application on Tomat7, right-click on the project and navigate to Run as -> Run on Server.

Fig. 10: How to Deploy Application on Tomcat

Fig. 10: How to Deploy Application on Tomcat

Tomcat will deploy the application in its web-apps folder and shall start its execution to deploy the project so that we can go ahead and test it in the browser.

5. Project Demo

Open your favorite browser and hit the following URL. The output page (i.e. the welcome screen) will be displayed.

http://localhost:8085/JavaServletSessionEx/

Server name (localhost) and port (8085) may vary as per your Tomcat configuration. Developers can debug the example and see what happens after every step. Enjoy!

Fig. 11: Welcome Form

Fig. 11: Welcome Form

Enter the username and submit the form. The success page will be displayed and we will get the response like a below image.

Fig. 12: Success Page

Fig. 12: Success Page

After 20 seconds, the session will be invalidated and the Servlet Session Timeout message will be displayed.

Fig. 13: Session Timeout Message

Fig. 13: Session Timeout Message

That’s all for this post. Happy Learning!!

6. Conclusion

In this section, developers learned the practical aspects of how to configure the timeout of the HTTP Session in a Servlet Java application. Developers can download the sample application as an Eclipse project in the Downloads section. I hope this article served you with whatever developers were looking for.

7. Download the Eclipse Project

This was an example of Servlet Session Timeout.

Download
You can download the full source code of this example here: ServletSessionTimeout
(No Ratings Yet)
1 Comment Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

1
Leave a Reply

avatar
1 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
Jorge Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
Jorge
Guest
Jorge

Thank you very much for the example. I think that the only “problem” with it is that, if I’m not wrong, the redirection will always happen, even if there has been some activity, after the specidied timeout. Isn’t it?