Servlet - Session Tracking

Last Updated : 12 May, 2026

Servlets are server-side Java programs used to handle client requests and generate dynamic responses. Since HTTP is a stateless protocol, the server does not remember previous client requests. Session Tracking is used to maintain and manage user-specific data across multiple requests so that web applications can remember user activities during a session.

  • Helps maintain client-server communication across multiple requests
  • Commonly used in login systems, shopping carts, and banking applications
  • Supports stateful behavior in web applications built on HTTP

Why is Session Tracking Required?

HTTP is a stateless protocol, which means the server does not remember previous requests made by the client. Because of this limitation, session tracking is required to maintain continuity between client-server interactions.

  • Maintains client-server relationship
  • Tracks user activities across requests
  • Used in e-commerce and banking applications
  • Helps manage authentication and authorization

Session Tracking Techniques

Servlet provides four different techniques for session tracking.

1. Cookies

Cookies are small pieces of data stored in the browser. The server sends cookies in the response, and the browser sends them back with future requests.

  • Stored on client-side browser
  • Used to identify users uniquely
  • Can be disabled by the client browser

Syntax:

Set-Cookie: user=GFG

2. Hidden Form Field

Hidden form fields store session information inside HTML forms using invisible input fields.

  • Data is hidden from users
  • Data is hidden from users
  • Mainly used in form-based applications

Syntax:

<input type="hidden" name="session" value="12345">

3. URL Rewriting

In URL rewriting, additional session data is appended to the URL as request parameters.

  • Works even if cookies are disabled
  • Session information is visible in the URL
  • Commonly used in basic session management

Syntax:

http://localhost:8080/app?sessionid=12345

4. HttpSession

HttpSession is the most commonly used session tracking technique in Servlets. It stores user-specific data on the server side and associates it with a unique session ID.

  • Stores session data on server side
  • More secure compared to URL rewriting
  • Used in login and authentication systems

Syntax:

HttpSession session = request.getSession();
session.setAttribute("username", "GFG");

Methods of HttpSession

MethodDescription
getAttribute(String name)Returns the object associated with the specified name
setAttribute(String name, Object value)Stores an object in the session
removeAttribute(String name)Removes a specific attribute from the session
invalidate()Invalidates the entire session
getId()Returns unique session ID
getCreationTime()Returns session creation time
getLastAccessedTime()Returns last accessed time of session
isNew()Checks whether session is newly created
setMaxInactiveInterval(int interval)Sets session timeout interval
getMaxInactiveInterval()Returns session timeout interval

Managing and Deleting Session Data

1. Remove Specific Session Attribute

Removes a particular attribute stored inside the current session.

session.removeAttribute("username");

2. Invalidate Entire Session

Destroys the complete session and removes all associated session data.

session.invalidate();

3. Set Session Timeout

Sets the maximum inactive time interval for the session in seconds.

session.setMaxInactiveInterval(1200);

4. Configure Session Timeout in web.xml

Defines the default session timeout duration for the entire web application.

<session-config>
<session-timeout>20</session-timeout>
</session-config>

Steps to Implement a Session Tracking Using HttpSession

Follow the below steps to implement Session Tracking using HttpSession in Servlet. we will create a session using the HttpSession object and track user visit information such as session creation time, last accessed time, and number of visits.

Step 1: Create Dynamic Web Project

Create a Dynamic Web Project in Eclipse.

  • Open Eclipse IDE
  • Click File -> New -> Dynamic Web Project
  • Enter project name as SessionTrackingGfg
  • Configure Apache Tomcat Server
  • Click Finish

Step 2: Create Servlet Class

Create GfgSession.java to create and manage the user session using the HttpSession object. This servlet stores session-related information such as session ID, creation time, last accessed time, and visit count, then displays the details in the browser response.

Java
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

// Extend HttpServlet class
public class GfgSession extends HttpServlet {

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

        // Create a session object if it is already not
        // created.
        HttpSession session = request.getSession(true);

        // Get session creation time.
        Date createTime
            = new Date(session.getCreationTime());

        // Get last access time of this web page.
        Date lastAccessTime
            = new Date(session.getLastAccessedTime());

        String title = "Welcome Back to geeksforgeeks";
        Integer visitCount = new Integer(0);
        String visitCountKey = new String("visitCount");
        String userIDKey = new String("userID");
        String userID = new String("GFG");

        // Check if this is new comer on your web page.
        if (session.isNew()) {
            title = "Welcome to GeeksForGeeks";
            session.setAttribute(userIDKey, userID);
        }
        else {
            visitCount = (Integer)session.getAttribute(
                visitCountKey);
            visitCount = visitCount + 1;
            userID
                = (String)session.getAttribute(userIDKey);
        }
        session.setAttribute(visitCountKey, visitCount);

        // Set response content type
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();

        String docType
            = "<!doctype html public \"-//w3c//dtd html 4.0 "
              + "transitional//en\">\n";

        out.println(
            docType + "<html>\n"
            + "<head><title>" + title + "</title></head>\n"
            +

            "<body bgcolor = \"#f0f0f0\">\n"
            + "<h1 align = \"center\">" + title + "</h1>\n"
            + "<h2 align = \"center\">Gfg Session Information</h2>\n"
            + "<table border = \"1\" align = \"center\">\n"
            +

            "<tr bgcolor = \"#949494\">\n"
            + "  <th>Session info</th><th>value</th>"
            + "</tr>\n"
            +

            "<tr>\n"
            + "  <td>id</td>\n"
            + "  <td>" + session.getId() + "</td>"
            + "</tr>\n"
            +

            "<tr>\n"
            + "  <td>Creation Time</td>\n"
            + "  <td>" + createTime + "  </td>"
            + "</tr>\n"
            +

            "<tr>\n"
            + "  <td>Time of Last Access</td>\n"
            + "  <td>" + lastAccessTime + "</td>"
            + "</tr>\n"
            +

            "<tr>\n"
            + "  <td>User ID</td>\n"
            + "  <td>" + userID + "</td>"
            + "</tr>\n"
            +

            "<tr>\n"
            + "  <td>Number of visits</td>\n"
            + "  <td>" + visitCount + "</td>"
            + "</tr>\n"
            + "</table>\n"
            + "</body>"
            + "</html>");
    }
}

 Step 3: Configure web.xml

Configure the servlet mapping inside the web.xml file so that the server can identify the servlet class and map it with the specified URL pattern.

XML
<web-app>
<servlet>
   <servlet-name>GfgSession</servlet-name>
   <servlet-class>GfgSession</servlet-class>
</servlet>

<servlet-mapping>
   <servlet-name>GfgSession</servlet-name>
   <url-pattern>/GfgSession</url-pattern>
</servlet-mapping>
</web-app>

Step 4: Run the Application

Run the project on the server using:

Run As -> Run on Server

if your IDE directly open the browser then the output is visible to us if not then Execute the following URL:

http://localhost:8080/SessionTrackingGfg/GfgSession

Output:

If we try to run the same servlet again, we will get the following result.

Explanation: The output displays the session details such as session ID, creation time, last accessed time, user ID, and visit count using the HttpSession object.

Comment