The HttpSession Interface in Servlet

Last Updated : 5 May, 2026

The HttpSession interface in Java Servlet is used to create and manage a session between a client and a server. It allows storing user-specific data across multiple requests, enabling stateful interaction in web applications. This is commonly used for features like login sessions, shopping carts, and user preferences.

  • Maintains user data across multiple HTTP requests.
  • Provides methods like setAttribute(), getAttribute(), and invalidate().
  • Automatically creates a unique session ID for each user.

HttpSession Working

The following diagram explains how Http Sessions work in servlets:

servlet_container

In above Diagram:

  • Multiple users (User 1, User 2) send requests to the server.
  • The Servlet container receives and processes these requests.
  • For each user, it creates a unique session ID.
  • Each session ID is linked to a specific user (Session id 1, Session id 2).
  • The session ID helps the server identify and track users separately.
  • User data is stored and maintained across multiple requests using the session.

Methods in HttpSession Interface

MethodDescription
public HttpSession getSession()Gets the HttpSession object. If the request doesn't have a session associated with it, a new session is created
public HttpSession getSession(boolean create)Gets the session associated with the request. If not already present, then a new one is created based on the value of the boolean argument passed into it
public String getId()Returns the unique session id
public long getCreationTime()It returns the time when this session was created, measured in milliseconds since midnight January 1, 1970 GMT.
public long getLastAccessedTime()It returns the time when this session was last accessed, measured in milliseconds since midnight January 1, 1970 GMT.
public long getLastAccessedTime()It returns the time when this session was last accessed, measured in milliseconds since midnight January 1, 1970 GMT.
public void invalidate()Invalidates the session

Advantages of Http Sessions in Servlet

  • Any kind of object can be stored into a session, be it a text, database, dataset etc.
  • Usage of sessions is not dependent on the client's browser.
  • Sessions are secure and transparent

Disadvantages of Http session

  • Performance overhead due to session object being stored on server
  • Overhead due to serialization and de-serialization of data

Example of Session tracking using HttpServlet Interface

In the below example the setAttribute() and getAttribute() methods of the HttpServlet class is used to create an attribute in the session scope of one servlet and fetch that attribute from the session scope of another servlet.

Step 1: Create HTML Form

  • User enters name in input field.
  • Form sends request to Servlet1 (/servlet1).
Java
<html>
<head>
<body>
<form action="servlet1">  
Name:<input type="text" name="userName"/><br/>  
<input type="submit" value="submit"/>  
</form>  
</body>
</html>

Step 2: First Servlet (First.java)

  • Receive user input
  • Create a session
  • Store data in session
  • Redirect to second servlet
Java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class First extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response) {
        try {
            response.setContentType("text/html");
            PrintWriter out = response.getWriter();

            // Get user input
            String name = request.getParameter("userName");

            // Print welcome message
            out.print("Welcome " + name);

            // Create session
            HttpSession session = request.getSession();

            // Store data in session
            session.setAttribute("uname", name);

            // Link to second servlet
            out.print("<br><a href='servlet2'>Visit Servlet 2</a>");

            out.close();

        } catch (Exception e) {
            System.out.println(e);
        }
    }
}

Step 3: Second Servlet (SecondServlet.java)

  • Retrieve existing session using request.getSession(false).
  • Fetch stored value using getAttribute("uname").
  • Display message using stored username.
Java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class SecondServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response) {
        try {
            response.setContentType("text/html");
            PrintWriter out = response.getWriter();

            // Get existing session (do not create new)
            HttpSession session = request.getSession(false);

            if (session != null) {
                String name = (String) session.getAttribute("uname");
                out.print("Hello " + name);
            } else {
                out.print("Session not found!");
            }

            out.close();

        } catch (Exception e) {
            System.out.println(e);
        }
    }
}

Step 4: Configure web.xml

Java
<web-app>

    <servlet>
        <servlet-name>s1</servlet-name>
        <servlet-class>First</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>s1</servlet-name>
        <url-pattern>/servlet1</url-pattern>
    </servlet-mapping>

    <servlet>
        <servlet-name>s2</servlet-name>
        <servlet-class>SecondServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>s2</servlet-name>
        <url-pattern>/servlet2</url-pattern>
    </servlet-mapping>

</web-app>

Step 5: Run the Application

  • Open index.html in browser.
  • Enter name and submit ->goes to Servlet1.
  • Click “visit” link -> goes to Servlet2.

Output: index.html :

Servlet1:

Servlet2:

Comment