Servlet - HttpSession Login and Logout Example

Last Updated : 13 May, 2026

Managing user sessions is an essential part of web applications to track user state across multiple requests. In Java Servlet-based applications, the HttpSession interface provides an easy and effective way to store session data such as user login status. This example demonstrates a simple login and logout implementation using HttpSession.

  • Maintains user-specific data across multiple requests using session handling.
  • Demonstrates how login creates a session and stores user information.
  • Shows how logout invalidates the session to securely end the user session.

HttpSession Interface

The HttpSession interface is used in Java Servlets to maintain user-specific data across multiple requests during a session. It allows storing and accessing user information on the server side.

  • Stores user data separately for each client session
  • Helps track user state like login status and preferences
  • Managed automatically by the servlet container

Creating a Session

A session is created after user login to maintain user-specific data across multiple requests. In Servlets. The HttpServletRequest provides various methods to create or access a session.

1. getSession()

Creates a new session if it does not exist, otherwise returns the existing session.

Syntax:

HttpSession session = request.getSession();

2. getSession(true)

Creates a new session if no session exists, otherwise returns the current session.

Syntax:

HttpSession session = request.getSession(true);

3. getSession(false)

Returns the existing session if available, otherwise returns null without creating a new session.

Syntax:

HttpSession session = request.getSession(false);

Invalidating the session

Once the user requests to logout, the session must be destroyed to remove all stored user data. This is done using the invalidate() method of the HttpSession interface.

void invalidate()

This method destroys the current session and removes all objects bound to it, effectively logging out the user.

Syntax:

HttpSession session = request.getSession();
session.invalidate();

When this invalidate method is called on the session, it removes all the objects that are bound to that session.

Alternative methods to logout the user

1. removeAttribute(String name)

Removes a specific attribute from the session (not the whole session), so other session data may still remain.

Syntax:

session.removeAttribute("user");

2. setMaxInactiveInterval(int interval)

Sets session timeout in seconds. If set to 0 or a small value, the session will expire automatically after inactivity.

Syntax:

session.setMaxInactiveInterval(0);

Steps to implements Servlet Login-Logout Example

We will create a basic Servlet program to display a welcome message for the validated users.

Step 1: Create Dynamic Web Project

  • Open Eclipse IDE
  • Create a project: Servlet_LoginLogout
  • Select: Dynamic Web Project
  • Click Finish

Your project directory is looks like after creation of Dynamic Project in your Eclipse IDE.

Project Structure

Step 2: Create Login Page (login.jsp)

Create login.jsp under the WebContent folder. This page accepts username and password from the user.

HTML
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<title>Login Page</title>
</head>
<body>

    <form action="login" method="post">

        <h3>Enter Login details</h3>

        <table>
            <tr>
                <td>User Name:</td>
                <td><input type="text" name="usName" /></td>
            </tr>
            <tr>
                <td>User Password:</td>
                <td><input type="password" name="usPass" /></td>
            </tr>

        </table>
        
        <input type="submit" value="Login" />

    </form>
</body>
</html>

Step 3: Create Login Servlet

Create LoginServlet under src folder Handles login request and creates session

Java
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("/login")
public class LoginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public LoginServlet() {
        super();
    }

    // doPost() method
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        // Set the content type of response to "text/html"
        response.setContentType("text/html");

        // Get the print writer object to write into the response
        PrintWriter out = response.getWriter();

        // Get the session object
        HttpSession session = request.getSession();

        // Get User entered details from the request using request parameter.
        String user = request.getParameter("usName");
        String password = request.getParameter("usPass");

        // set the user in this session and redirect to welcome page
        if (password.equals("geek")) {
            session.setAttribute("user", user);
            response.sendRedirect("welcome.jsp?name=" + user);
        }
        // If the password is wrong, display the error message on the login page.
        else {
            RequestDispatcher rd = request.getRequestDispatcher("login.jsp");
            out.println("<font color=red>Password is wrong.</font>");
            rd.include(request, response);
        }
        // Close the print writer object.
        out.close();
    }
}

Explanation: This servlet handles user login by validating the password and creating an HttpSession for a successful login. It then redirects the user to the welcome page or shows an error message if the login fails.

Step 4: Create Welcome Page

Create welcome.jsp under the WebContent folder to display the welcome message and logout button.

HTML
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<title>Welcome Page</title>
</head>
<body>

    <form action="logout" method="get">

        <h2>
            Hello
            <%=request.getParameter("name")%>!
        </h2>
        <h3>Welcome to GeeksforGeeks..</h3>

        <br> <input type="submit" value="Logout" />
    </form>
    
</body>
</html>

Step 5: Create Logout Servlet

Handles logout request and Destroys session using invalidate()

Java
import java.io.IOException;
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("/logout")
public class LogoutServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

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

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

        // Destroy session if it exists
        if (session != null) {
            session.invalidate();
        }

        // Redirect or show message
        response.setContentType("text/html");
        response.getWriter().println("You have been successfully logged out.");
    }
}

Explanation: This servlet destroys the current session using invalidate() and logs the user out of the application.

Step 6: Run the Project

  • Right click project -> Run As -> Run on Server
  • Open browser:

http://localhost:8080/Servlet_LoginLogout/login.jsp

Output:

Your Login page will be disappear on your screen.

Login Page

Enter the user name and password and click on Login.

Login with User details

Give the Password as "geek" as we are validating against it, if not it throws an error like below.

Incorrect_password

Enter the correct credentials and log in.

Welcome Page

The User name which we set in the session object is displayed with a welcome message. Click on Logout.

Logout_success

Now, if you check the console, it prints the session object values.

Console

Explanation:

  • As you can see, "getSession()" returned the existing session object.
  • After the invalidate method, as there is no session, it returned "null".
Comment