Lecture 28: Session Tracking using HttpSession

BMC201 - Web Technology

Mr. Prashant Kumar Nag

2026-03-24

Lecture 28

Session Tracking using HttpSession

Week 9 | Unit III: Servlets
BMC201 - Web Technology
Mr. Prashant Kumar Nag, Assistant Professor

Learning Objectives


  • Explain HttpSession architecture and lifecycle in servlet container
  • Use session APIs correctly with strong null-safety patterns
  • Implement authentication, authorization, timeout, and logout flows
  • Analyze session security risks: fixation, hijacking, stale sessions
  • Apply scalable session design principles for distributed deployments
  • Build exam-quality conceptual and code-level answers

Unit III Topic Traceability


Primary syllabus mapping:

  • Session tracking with HttpSession

Dependency relationship:

  • uses cookie concepts from lecture 27
  • supports JSP/MVC control flow in lecture 29 onward

Why HttpSession is Needed


Cookie-only tracking is insufficient for secure, mutable, server-controlled state.

HttpSession provides:

  • server ownership of user state
  • reduced client tampering risk
  • controlled lifecycle and invalidation
  • centralized management for authenticated flows

Session Architecture in Container


flowchart LR
  A[Browser Request] --> B[Servlet Container]
  B --> C[Session ID Resolver]
  C --> D[Session Store]
  D --> E[HttpSession object]
  E --> F[Servlet/JSP Business Logic]

How Session Identity Works


Session identity is maintained by a session id token, commonly JSESSIONID.

Transport path:

  • primarily cookie
  • optionally URL rewriting for fallback

The token points to server-side state; business data is not stored in token itself.

Session Lifecycle States


stateDiagram-v2
  [*] --> Created: request.getSession()/getSession(true)
  Created --> Active: container returns session id
  Active --> Active: subsequent valid requests update last accessed time
  Active --> Expired: max inactive interval exceeded
  Active --> Invalidated: invalidate() or security reset
  Expired --> [*]
  Invalidated --> [*]

HttpSession is created by the container, remains active while reused by valid requests, and is destroyed either by timeout or explicit invalidation.

Core HttpSession API Map


API Semantics Typical Use
getSession() fetch or create post-login creation
getSession(false) fetch only if exists protected page checks
setAttribute add/update key user id, role
getAttribute read key auth/authorization checks
removeAttribute remove key transient cleanup
invalidate destroy session logout and security reset
setMaxInactiveInterval timeout in seconds inactivity policy

Create Session After Authentication


HttpSession session = request.getSession(true);
session.setAttribute("userId", user.getId());
session.setAttribute("role", user.getRole());
session.setAttribute("loginAt", java.time.Instant.now());

Read Session with Null Safety


HttpSession session = request.getSession(false);
if (session == null) {
  response.sendRedirect(request.getContextPath() + "/login.jsp");
  return;
}
Long userId = (Long) session.getAttribute("userId");

Update and Remove Attributes


HttpSession session = request.getSession(false);
if (session != null) {
  session.setAttribute("lastAction", "PROFILE_UPDATED");
  session.removeAttribute("temporaryOtp");
}

Remove transient values as soon as they are no longer required.

Session Invalidation Semantics


invalidate() should be treated as security boundary reset.

Use cases:

  • explicit logout
  • password change
  • role changes requiring re-auth
  • suspicious activity detection
HttpSession session = request.getSession(false);
if (session != null) session.invalidate();

Authentication Flow with HttpSession


sequenceDiagram
  participant U as User
  participant L as LoginServlet
  participant P as ProtectedServlet

  U->>L: POST /login credentials
  L-->>U: create session + redirect /dashboard
  U->>P: GET /dashboard with session id
  P-->>U: authorize and render response

Protected Endpoint Guard Pattern


HttpSession session = request.getSession(false);
boolean loggedIn = session != null && session.getAttribute("userId") != null;

if (!loggedIn) {
  response.sendRedirect(request.getContextPath() + "/login.jsp");
  return;
}

Role-Based Authorization Check


String role = (String) session.getAttribute("role");
if (!"ADMIN".equals(role)) {
  response.sendError(HttpServletResponse.SC_FORBIDDEN, "Access denied");
  return;
}

Authentication verifies identity; authorization enforces privilege.

Why Use Servlet Filters for Session Checks


Centralizing auth checks in filter avoids repeated boilerplate across servlets.

Benefits:

  • consistency
  • easier audits
  • lower maintenance cost

Auth Filter Example


HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
HttpSession session = req.getSession(false);

boolean loggedIn = session != null && session.getAttribute("userId") != null;
if (!loggedIn) {
  res.sendRedirect(req.getContextPath() + "/login.jsp");
  return;
}
chain.doFilter(request, response);

Session Timeout Configuration


HttpSession session = request.getSession();
session.setMaxInactiveInterval(20 * 60); // 20 minutes
<session-config>
  <session-timeout>20</session-timeout>
</session-config>

Graceful Session Expiration Handling


HttpSession session = request.getSession(false);
if (session == null) {
  request.setAttribute("msg", "Session expired. Please login again.");
  request.getRequestDispatcher("/login.jsp").forward(request, response);
  return;
}

Better UX reduces user confusion and support tickets.

Session Fixation Attack and Mitigation


Fixation risk: attacker forces victim to use known session id.

Mitigation at login:

  1. invalidate pre-auth session
  2. create fresh session id
  3. bind authenticated identity to new session

Fixation Mitigation Code


HttpSession old = request.getSession(false);
if (old != null) {
  old.invalidate();
}
HttpSession fresh = request.getSession(true);
fresh.setAttribute("userId", user.getId());

Session Hijacking Risk Controls


  • enforce HTTPS end-to-end
  • set secure cookie flags for session id
  • short inactivity timeout for sensitive applications
  • logout invalidates server session and client token
  • monitor suspicious IP/device/session anomalies

What to Store in Session


Store Avoid
user id and role password or secrets
compact workflow state large object graphs
one-time flash messages heavy report data
authorization cache keys permanent records

Relationship with Cookie Layer


HttpSession uses cookie primarily as transport for session id.

If cookie unavailable:

  • container can rewrite URL using encodeURL
  • security and URL hygiene concerns increase
String safeUrl = response.encodeURL("dashboard.jsp");
response.sendRedirect(safeUrl);

Session Debugging Checklist


Check sequence:

  1. session created at login success?
  2. session id present in next request?
  3. auth filter/guard ordering correct?
  4. timeout policy too aggressive?
  5. logout invalidation functioning?

Frequent Implementation Errors


  • using getSession() in guards and creating empty sessions
  • missing null checks with getSession(false)
  • forgetting authorization after authentication
  • keeping stale sessions active after role changes
  • storing oversized data causing memory pressure

Exam and Viva Questions


Prepare long-answer quality responses:

  1. explain HttpSession lifecycle with diagram
  2. compare getSession() and getSession(false)
  3. design auth + authorization + logout flow
  4. discuss session fixation and mitigation
  5. explain scaling concerns for session-based apps

Hands-On Lab Task


Implement secure module:

  • login servlet + role attribute
  • auth filter for protected routes
  • admin authorization check
  • configurable timeout behavior
  • logout and forced re-login after role change

Stretch objective:

  • simulate fixation mitigation and verify session id rotation.

Summary


You can now:

  • architect session management beyond basic syntax
  • implement robust and secure servlet session flows
  • reason about lifecycle, security, and scaling trade-offs
  • answer Unit III concepts at MCA standard depth