In this article, we are going to understand how to maintain a session by using an HttpSession object.
Using an object of HttpSession interface, web container can locate if there an existing session associated with the user
and if it doesn't find an existing session, it creates one.
This HttpSession object helps in storing a user information or a session data, to maintain its session and differentiate it from other users.
The new session exists for a certain interval and it survives even when different requests are made by the same user.
Methods of HttpServletRequest used to create a new session
This method returns an existing session associated with the request or it creates a new session by returning an object of HttpSession
(if it is unable to locate a session associated with the request).
Passing true to this method, it returns the existing session associated with the user or it creates a new session by returning an object of
HttpSession(if it is unable to locate a session associated with the request).
Passing false to this method, it returns the existing session associated with the user or it returns a null(if it is unable to locate a session associated with the request).
Some useful methods available to session object.
The methods in the table below are part of javax.servlet.http.HttpSession interface. Hence, these methods are available to the JSP implicit
session object, which is a type of HttpSession.
voidsetAttribute(String name, Object value)
This method sets an object with a name in a session.
This method gets an object stored in a session with a name, or null.
This method removes an object with a name from the session.
This method returns the last time(since midnight Jan 1, 1970 in milliseconds) since a client accessed this session.
This method gets the time(in seconds) before servlet contained invalidates the session.
This method sets the time between client requests before the servlet container invalidates the session.
This method gets the creation time of the current session, since 1970 in milliseconds.
This method returns the ServletContext to the current session.
This method gives a true if the current session is new and client doesn't know about it.
Maintaining a Session within a Servlet
We are creating a Servlet extending the HttpServlet abstract class. HttpServlet class extends GenericServlet abstract class.
This class named MyServlet1.java, implements doGet() method of HttpServlet class to handle the default get request
made by the client after executing the this Servlet.
This Servlet does the following tasks -
It creates a variable counter to count the number of visits of the user on this website.
It calls the getSession(boolean) method to locate an existing session associated with the user.
If the getSession(boolean) is unable to locate any existing session with the current user, it creates one and the information about this session is displayed,
or, if it has located an existing session with the current user, it displays the session information and number of times user has visited this website.
public class MyServlet1 extends HttpServlet
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
PrintWriter out = response.getWriter();
//Creates a variable to count the number of visits of the user
int counter = 0;
//Creates a session object
HttpSession session = request.getSession(true);
out.println("<b> Welcome, </b> " );
out.println("<br/> <br/> <br/> ");
boolean sessionInfo = session.isNew();
out.println("Is this a new session = " + sessionInfo);
out.println("Session ID = " + session.getId());
out.println("This session was created = " + new Date(session.getCreationTime()));
out.println("Last time when this session was accessed = " + new Date(session.getLastAccessedTime()));
out.println("Maximum time for which this session can be inactive = " + session.getMaxInactiveInterval() + " seconds");
out.println("<br/> <br/> <br/> ");
counter = counter + 1;
out.println("<b> This is your first visit to this website </b>");
counter = (int)session.getAttribute("visit");
counter = counter + 1;
out.println("<b> Number of times you have visited this website : <b> "+ counter);
Directory Structure of Servlet files
The diagram above depicts how to arrange the Servlet files in a specific directory structure, as per Java Servlet Specification-
Project Folder - We have created a project folder named SessionEx within
the webapps folder of Tomcat installation folder. This folder contains the Servlet class(.java) file and WEB-INF folder.
WEB-INF - Within your project folder, you create another folder named WEB-INF and this folder should contain the deployment descriptor file(web.xml) of your Java Servlet program.
classes - Within the WEB-INF folder you should create a folder named classes. This folder should contain the compiled(.class) form of your Java Servlet class.
Creating the Deployment Descriptor file
As per the Java Servlet specifications, every web application based on Servlet must have a Deployment Descriptor file(an XML file) named web.xml.
So, let's create one -
In deployment descriptor file, <servlet> has two child tags <servlet-name> and <servlet-class> :
<servlet-name> tag is used to specify a unique name for our Servlet class.
<servlet-class> tag is used to specify the full qualified name of the Servlet class .
The child tag <servlet-name> of <servlet> tag is matched with the <servlet-name> child tag of
<url-pattern> child tag is used to specify the URL to access Servlet, Hence -
We have named this URL Serv1. to access the first servlet, MyServlet1.java
Setting the classpath
Much of the support for developing the web applications based on the Java Servlet technology does not come with the core Java.
Hence, in order to compile the Servlet programs, we have to set the classpath to a jar file named
This jar file provides all the classes that are required for the Servlet programming and it comes within the lib Folder of
Tomcat installation folder.
For example, in our case we have installed Tomcat Web Server within the C: Drive, hence the path to our lib folder containing the servlet-api.jar is - C:\apache-tomcat-9.0.2\lib
There are two ways to set the classpath -
You could set the classpath by entering this command at the Command Prompt, but this only temporarily sets the classpath to the path of servlet-api.jar file. If you restart your system, you will have to set the classpath again.
After setting the classpath, you need to compile the both of the Servlet class by entering the command at the folder where you've stored the Servlet class file.
javac -d WEB-INF/classes MyServlet1.java
Executing the Servlet
Executing the webpage containing the Servlet for the first time gives us the information about the new session created.
This page also gives us a personalised welcome message on our first visit. This Servlet also maintains a counter which displays the number of times a user
has visited this webpage.
On refreshing this webpage the Servlet gives us current value of the counter i.e. the number of times we have visited this webpage and the information about the current session.
This counter is maintained by creating an HttpSession object