Lecture 26: Redirecting Requests & Request Dispatching

BMC201 - Web Technology

Mr. Prashant Kumar Nag

2026-03-10

Lecture 26

Redirecting Requests & Request Dispatching

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

Learning Objectives


  • Formally define redirect, forward, and include in servlet architecture
  • Analyze control transfer from protocol and container perspective
  • Explain the impact of each strategy on URL, request scope, and caching
  • Apply Post-Redirect-Get (PRG) pattern with reasoning, not just memorized syntax
  • Select routing strategy for real application scenarios
  • Troubleshoot routing bugs using deterministic checklist

Unit III Topic Traceability


Syllabus mapping:

  • Redirecting requests to other resources

Prerequisites used:

  • HTTP methods and request-response model
  • Servlet lifecycle and HttpServletRequest/HttpServletResponse

Forward dependency:

  • Session tracking topics in lectures 27 and 28

Why Request Routing is a Core Skill


In enterprise applications, most defects are flow defects, not syntax defects.

Typical failures caused by poor routing choices:

  • duplicate inserts after browser refresh
  • lost validation messages
  • stale URLs causing incorrect bookmarking
  • accidental redirect loops
  • inconsistent security flow after login/logout

Routing is therefore an architectural decision, not a minor API choice.

Where Routing Happens in MVC


flowchart LR
  A[Client Request] --> B[Front Controller / Servlet]
  B --> C[Service Layer]
  C --> D{Outcome}
  D -->|Validation errors| E[Forward to JSP]
  D -->|State changed| F[Redirect to GET URL]
  E --> G[HTML with request scope messages]
  F --> H[Fresh GET request]
  H --> I[Stable response]

Formal Definitions


Term Definition Initiator
Redirect HTTP response instructing client to request a different URI Server, executed by browser
Forward Internal dispatch of same request/response to another resource Servlet container
Include Internal inclusion of another resource output into current response Servlet container

Redirect Internal Mechanics


sendRedirect() behavior in sequence:

  1. Container sets status and Location header
  2. Response is committed to client
  3. Browser creates a brand-new request
  4. Target resource executes independently

Consequences:

  • request scope does not survive
  • request method may change based on status code behavior
  • network round-trip is required

Protocol Sequence: Redirect


sequenceDiagram
  participant B as Browser
  participant S as Source Servlet
  participant T as Target Resource

  B->>S: POST /student/create
  S-->>B: 302 Location: /student/list
  B->>T: GET /student/list
  T-->>B: 200 OK + HTML

Forward Internal Mechanics


RequestDispatcher.forward() behavior:

  1. Current servlet passes control internally
  2. Same request/response objects are reused
  3. Target resource receives all request attributes
  4. Response to browser is generated once

Consequences:

  • better performance than redirect in most cases
  • URL generally stays at original route
  • ideal for controller-to-view rendering

Protocol Sequence: Forward


sequenceDiagram
  participant B as Browser
  participant C as Controller Servlet
  participant V as JSP View

  B->>C: POST /student/create
  C->>V: forward(request, response)
  V-->>B: 200 OK + HTML response

Include and Response Composition


include() is for compositional rendering, not flow termination.

Use cases:

  • common header/footer fragments
  • audit snippets or banners
  • template blocks in legacy JSP apps

Important behavior:

  • control returns to caller after include
  • included resource should not commit independent final response

Essential API Usage


// Redirect
response.sendRedirect(request.getContextPath() + "/student/list");

// Forward
request.getRequestDispatcher("/views/student-form.jsp").forward(request, response);

// Include
request.getRequestDispatcher("/views/common/header.jsp").include(request, response);

Decision Matrix


Criterion Redirect Forward Include
Browser performs second request Yes No No
URL updates Yes No No
Request attributes available No Yes Yes
Cross-application/external target Yes No No
Suitable for Post-Redirect-Get (PRG) Yes No No
Suitable for templating No No Yes

Redirect Status Codes and Semantics


Relevant HTTP status semantics:

  • 301: permanent move, cacheable by clients/proxies
  • 302: temporary redirect (commonly used by sendRedirect)
  • 303: explicit instruction to use GET for follow-up
  • 307/308: method-preserving redirects

For MCA-level understanding, method preservation and cache behavior are critical distinctions.

Why Post-Redirect-Get (PRG) Solves Duplicate Submission


Without Post-Redirect-Get (PRG):

  • POST response page is tied to mutation request
  • refresh triggers browser re-submission prompt
  • accidental duplicate transaction risk

With Post-Redirect-Get (PRG):

  • mutation handled in POST
  • user lands on idempotent GET page
  • refresh remains safe

Post-Redirect-Get (PRG) Flow Diagram


flowchart LR
  A[POST /save] --> B[Server validates and persists]
  B --> C[302 redirect to /list]
  C --> D[GET /list]
  D --> E[Render stable list view]

Post-Redirect-Get (PRG) Implementation Pattern


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

  ValidationResult result = validator.validate(request);
  if (!result.isValid()) {
    request.setAttribute("errors", result.getErrors());
    request.getRequestDispatcher("/views/student-form.jsp").forward(request, response);
    return;
  }

  studentService.create(result.toStudent());
  response.sendRedirect(request.getContextPath() + "/student/list");
}

Scope and Data Propagation Rules


Scope Survives Forward Survives Redirect Typical Use
Request scope Yes No validation errors, form inputs
Session scope Yes Yes login state, flash messages
Application scope Yes Yes shared config references

Flash Message Pattern


HttpSession session = request.getSession();
session.setAttribute("flashSuccess", "Student created successfully");
response.sendRedirect(request.getContextPath() + "/student/list");
<c:if test="${not empty sessionScope.flashSuccess}">
  <div class="alert alert-success">${sessionScope.flashSuccess}</div>
</c:if>
<c:remove var="flashSuccess" scope="session"/>

Path Resolution Strategy


Path mistakes are among the top causes of navigation failures.

Best practice:

  • use context-relative paths for redirects with getContextPath()
  • use app-internal absolute dispatcher paths like /views/x.jsp
  • avoid brittle hard-coded deployment paths

Case Study: Login Flow


Design goal:

  • wrong credentials -> display error on same login page
  • correct credentials -> move to dashboard safely

Correct strategy:

  • failure: forward with request error attribute
  • success: redirect to dashboard GET endpoint

Case Study: Update Profile


Requirement: after update, user should bookmark resulting profile URL.

Routing choice:

  • POST /profile/update performs update
  • redirect to GET /profile/{id}

This ensures canonical URL and refresh-safe behavior.

Case Study: Shared Layout


request.getRequestDispatcher("/views/common/header.jsp").include(request, response);
request.getRequestDispatcher("/views/dashboard-body.jsp").include(request, response);
request.getRequestDispatcher("/views/common/footer.jsp").include(request, response);

Demonstrates include-based composition in traditional JSP rendering.

Common Anti-Patterns


  • forwarding after response commit
  • redirecting and then still writing response body
  • assuming request attributes survive redirect
  • implementing state-changing actions through GET
  • redirect loops due to missing route guards

Structured Debug Checklist


Investigation order:

  1. confirm actual status code and headers
  2. verify final URL in browser network tab
  3. inspect request attributes at target
  4. validate path/context correctness
  5. check for double-dispatch or missing return

This approach reduces random trial-and-error debugging.

Routing and Security Interactions


Security-sensitive observations:

  • never include confidential tokens in redirect query strings
  • guard post-login redirects against open redirect attacks
  • after logout, redirect to public page and invalidate session
  • ensure auth checks on redirected target resources

Exam-Oriented Questions


Prepare detailed answers for:

  1. distinguish redirect and forward with request lifecycle
  2. explain Post-Redirect-Get (PRG) with sequence flow
  3. discuss request/session scope behavior in navigation
  4. explain include usage with example
  5. list routing anti-patterns and fixes

Hands-On Practice Task


Implement StudentRegistrationServlet:

  • invalid form -> forward with error map
  • valid form -> persist and redirect to list
  • show one-time flash message on list
  • add safe default redirect target after auth

This single exercise integrates all lecture concepts.

Summary


After this lecture, you should be able to:

  • reason about routing at protocol and container level
  • apply redirect/forward/include with correctness
  • design Post-Redirect-Get (PRG)-based mutation workflows
  • debug and secure servlet navigation in production-like scenarios