Lecture 22: Session Tracking with HttpSession

BMC201 - Web Technology

Mr. Prashant Kumar Nag

2026-02-26

Lecture 22

Session Tracking with HttpSession

Week 8 | Unit III: Web App Development (Servlets + JSP)
BMC201 - Web Technology
Mr. Prashant Kumar Nag, Assistant Professor

Learning Objectives


  • Create and use HttpSession
  • Store/retrieve server-side user state
  • Configure timeout and invalidate session

Prerequisites


  • Java basics: classes, methods, objects, and exception handling
  • HTTP request-response fundamentals from Unit I/II web context
  • Revision of Lecture 21 before moving into Session Tracking with HttpSession

Syllabus Mapping


  • Unit III topic focus: Session Tracking with HttpSession
  • CO alignment: implementation understanding + architecture reasoning
  • Assessment alignment: short definitions + long implementation/design questions

Agenda


  • 5-minute recap from previous lecture
  • Concept deep dive: Session Tracking with HttpSession
  • Code/configuration walkthrough and output analysis
  • Debug checklist and exam-oriented summary

Introduction


HttpSession keeps per-user state on the server while the browser carries only JSESSIONID.

This model reduces direct client-side exposure of user data and supports controlled lifecycle management through timeout and explicit invalidation.

Think About It


Should cart, role, and authentication state all live in session, or should some data be derived per request?

Types of Session Tracking


Type Where State Lives Strength Limitation
Cookies Browser Simple and automatic per request Client-side exposure and size limits
URL Rewriting URL/query/path Works when cookies are disabled URL clutter and leakage risk
Hidden Fields HTML forms Easy for form workflows Only works on form submissions
HttpSession Server Better control and security for user state Server memory usage per active session

Lecture 22 focus: HttpSession as the primary server-side tracking mechanism.

HttpSession API


sequenceDiagram
    participant B as Browser
    participant C as Servlet Container
    participant S as Servlet
    B->>S: Login request
    S->>C: request.getSession()
    C-->>S: HttpSession (JSESSIONID)
    S->>C: setAttribute("user", ...)
    S-->>B: Response + JSESSIONID cookie
    B->>S: Next request with JSESSIONID
    S->>C: getAttribute("user")

  • HttpSession stores user state on server side
  • Browser only carries session identifier (JSESSIONID)
  • Always invalidate session on logout or privilege change

HttpSession Lifecycle APIs That Matter


HttpSession existing = request.getSession(false); // do not create new
HttpSession session = request.getSession();       // create if absent
session.setAttribute("user", userDto);
session.setMaxInactiveInterval(15 * 60);
session.invalidate();
  • Use getSession(false) for protected endpoints to avoid accidental session creation
  • Store only required session data; avoid large objects
  • Regenerate or invalidate session on login/logout transitions

HttpSession API Comparison


API/Operation Behavior Best Use Risk if Misused
getSession() Returns existing or creates new session Login flow and first authenticated step Unwanted session creation on public pages
getSession(false) Returns existing, does not create Protected endpoints, auth checks Null handling required
setAttribute() Stores object in session User profile/role/context Oversized object storage
invalidate() Destroys current session Logout and privilege reset If skipped, stale/unsafe session reuse

Operational rule: choose API variant intentionally based on endpoint responsibility.

Code Walkthrough


HttpSession session = request.getSession();
session.setAttribute("user", "prash");
session.setAttribute("role", "student");
String u = (String) session.getAttribute("user");
session.setMaxInactiveInterval(900);
if ("logout".equals(request.getParameter("action"))) {
    session.invalidate();
}

Memory Booster


Syllabus memory points for Session Tracking with HttpSession:

  • Core recall: setAttribute() and getAttribute()
  • Exam compare: Cookie-based tracking vs server-side HttpSession
  • Practical anchor: Implement session-based login state and logout invalidation

Live Demo


Live implementation for Session Tracking with HttpSession:

Open Demo: Lecture 22 - Session Tracking with HttpSession

Demo flow:

  • Login to create session and set user/role
  • Access protected resource with active JSESSIONID
  • Invalidate session and verify protected access is blocked

Takeaway: session state is server-managed and must be explicitly closed.

Resources & References


Structured Debug Checklist


  1. verify the primary API usage for Session Tracking with HttpSession is correct (imports, method names, config)
  2. check request/bean/session flow and object lifecycle assumptions
  3. inspect server logs for the first exception (not just the final symptom)
  4. reproduce one failing case and one passing case before finalizing fixes

Exam Preparation Questions: Short


  • Define Session Tracking with HttpSession with one practical use case.
  • Write/identify the key API or construct: setAttribute() and getAttribute().
  • Differentiate: Cookie-based tracking vs server-side HttpSession.
  • Mention one common implementation error and correction.

Exam Preparation Questions: Long


  • Explain Session Tracking with HttpSession with architecture/flow and implementation steps.
  • Write a structured answer comparing two approaches used in this topic.
  • Discuss debugging strategy for this topic with likely failure points.

Practice Task


  • Implement: Implement session-based login state and logout invalidation.
  • Add console/log output to validate flow step-by-step.
  • Document one bug you encountered and the exact fix.

Checklist


Can you:

  • explain Session Tracking with HttpSession in your own words?
  • implement a basic example end-to-end?
  • identify and fix one common runtime issue?

Next Lecture


  • Topic: Lecture 23 - JSP Introduction & Implicit Objects
  • Preparation required: revise this lecture summary and code walkthrough

Questions?

Next: Lecture 23