Implementing Session-Based Access Control in Java Servlets

Project Overview

This tutorial demonstrates how to implement an authentication mechanism using Java Servlets and HttpSession. The objective is to ensure that a user logs in once and gains access to protected resources within the same session. If a user attempts to access a protected resource without an active session, they are redirected to the login page.

Project Structure

The application consists of a login page, a protetced dashboard, a servlet handling authentication, a servlet managing access control, and a data transfer object for user details.

Login Page (login.html)

The entry point of the application. It collects credentials and submits them to the authentication controller.


<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>System Login</title>
</head>
<body>
    <form action="auth.do" method="post">
        <div>
            <label>Username: </label>
            <input type="text" name="userId" />
        </div>
        <div>
            <label>Password: </label>
            <input type="password" name="userPass" />
        </div>
        <div>
            <button type="submit">Sign In</button>
        </div>
    </form>
</body>
</html>

Protected Resource (dashboard.html)

This file represents the secure content loccated within the WEB-INF directory to prevent direct public access.


<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Dashboard</title>
</head>
<body>
    <h1>Welcome to the Dashboard</h1>
    <p>This is a protected area accessible only after login.</p>
</body>
</html>

Authentication Controller (AuthServlet.java)

This servlet processes the login request. It validates the credentials against hardcoded values. Upon successful validation, it creates a sesssion, stores the user profile, and redirects to the dashboard. On failure, it returns to the login page.

package com.example.controller;

import com.example.model.UserProfile;
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;
import java.io.IOException;

@WebServlet("/auth.do")
public class AuthServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        
        String id = request.getParameter("userId");
        String pass = request.getParameter("userPass");

        // Hardcoded validation check
        if ("admin".equals(id) && "secret".equals(pass)) {
            // Create a session and store the user profile
            UserProfile profile = new UserProfile(id, "Administrator");
            HttpSession session = request.getSession();
            session.setAttribute("currentUser", profile);

            // Redirect to the dashboard controller
            response.sendRedirect(request.getContextPath() + "/dashboard.do");
        } else {
            // Authentication failed, redirect back to login
            response.sendRedirect(request.getContextPath() + "/login.html");
        }
    }
}

Dashboard Controller (DashboardServlet.java)

This servlet acts as a gatekeeper for the protected resource. It checks the HttpSession for the existence of the user attribute. If found, it forwards the request to the protected HTML file; otherwise, it redirects the user to the login page.

package com.example.controller;

import com.example.model.UserProfile;
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;
import java.io.IOException;

@WebServlet("/dashboard.do")
public class DashboardServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        
        HttpSession session = request.getSession(false);
        
        // Check if session exists and contains the user attribute
        if (session != null && session.getAttribute("currentUser") != null) {
            // User is authenticated, forward to protected resource
            request.getRequestDispatcher("/WEB-INF/dashboard.html").forward(request, response);
        } else {
            // User is not authenticated, redirect to login
            response.sendRedirect(request.getContextPath() + "/login.html");
        }
    }
}

Data Model (UserProfile.java)

A simple Java Bean (POJO) used to encapsulate user information. It implements Serializable to support session persistence if required by the servlet container.

package com.example.model;

import java.io.Serializable;

public class UserProfile implements Serializable {
    private String username;
    private String fullName;

    public UserProfile() {
    }

    public UserProfile(String username, String fullName) {
        this.username = username;
        this.fullName = fullName;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getFullName() {
        return fullName;
    }

    public void setFullName(String fullName) {
        this.fullName = fullName;
    }
}

Tags: Java Servlets HttpSession Web Security J2EE Authentication

Posted on Mon, 05 Oct 2026 16:17:38 +0000 by project3