Nearby lessons

14 of 34

Servlet - RequestDispatcher (forward and include)

📌 What You Will Learn
  • Understand the forward mechanism
  • Understand the include mechanism
  • Learn forward vs include vs sendRedirect differences
  • See complete working code examples

RequestDispatcher enables forwarding requests between servlets and including responses from other resources. This lesson covers forward, include, and Foreign RequestDispatcher with complete code examples.

Forward Mechanism

If Servlet-1 handles preliminary processing and Servlet-2 provides the complete response, use the forward mechanism.

Key points about forward:

  • The same request object is forwarded to the second servlet
  • Information sharing between components is possible via request-scoped attributes
  • SecondServlet has complete control on the response object — can change response headers
  • After committing the response, forward is not allowed (throws IllegalStateException)
  • Recursive forward calls cause StackOverflowError

Demo: Basic Forward

Example02
Loading editor…

SecondServlet.java

Example03
Loading editor…

Demo: Login Validation with Forward

login.html: Sends GET request with username and password

inbox.jsp: <h1>This is inbox page you can get all mail services</h1>

error.jsp: <h1>This is error page your credentials are invalid please login again here <a href="/advapps3D/login.html">LOGIN</a></h1>

login.html Form

Example05
Loading editor…

ValidateServlet.java

Forward rules:

  • Case 1: Just before forwarding, the response is cleared — any response added by FirstServlet won't be displayed
  • Case 2: The same request object is forwarded — information sharing via request-scoped attributes is possible
  • Case 3: SecondServlet has complete control on the response object — can change headers added by FirstServlet
  • Case 4: After committing the response, forward is not allowed (throws IllegalStateException)
  • Case 5: Recursive forward calls always cause StackOverflowError
Example06
Loading editor…

Request Attributes Sharing

Sharing data via request attributes:

  • FirstServlet: req.setAttribute("count", 10);
  • SecondServlet: Object o = req.getAttribute("count");

Case 6: After forward, control returns to FirstServlet

Any remaining statements execute, but:

  • Writing to response is ignored by the web container
  • If an exception occurs, the exception info is displayed instead of SecondServlet's response
  • Only if all remaining statements execute successfully will SecondServlet's response be displayed
Example07
Loading editor…

Forward Attributes Added by Web Container

While forwarding, the web container adds attributes to the request scope to make original request information available to the second servlet:

  • javax.servlet.forward.request_uri
  • javax.servlet.forward.context_path
  • javax.servlet.forward.servlet_path
  • javax.servlet.forward.path_info
  • javax.servlet.forward.query_string

Note: If RequestDispatcher is obtained via getNamedDispatcher(), no attributes are added.

Example08
Loading editor…

Include Mechanism

Use include to embed the response of other resources in the current response. Best suited for including banner information like copyright, logo, etc.

  • The servlet that receives the request initially is responsible for the response
  • After committing the response, you can perform include() but not forward()
  • In include, the second servlet does not have complete control on the response — it cannot change response headers

Demo: Include

Output: Hello This is FirstServlet → This is Second Servlet → Hi This is First Servlet again

Example10
Loading editor…

SecondServlet.java (Include)

Include attributes added by web container:

  • javax.servlet.include.request_uri
  • javax.servlet.include.context_path
  • javax.servlet.include.servlet_path
  • javax.servlet.include.path_info
  • javax.servlet.include.query_string
Example11
Loading editor…

Foreign RequestDispatcher

To communicate with resources of other applications within the same server, use Foreign RequestDispatcher (FRD).

Example12
Loading editor…

SecondServlet.java (Foreign RequestDispatcher)

Access at: http://localhost:7777/advapps3H/test1

Notes:

  • RequestDispatcher works only within the same server — both applications must be deployed on the same server
  • Most web servers don't support cross-context communication by default (security reasons) — throws NullPointerException
  • In Tomcat, add <Context crossContext="true"> in conf/context.xml
  • After committing the response, neither sendRedirect() nor forward() is allowed
Example13
Loading editor…

Forward vs Include Comparison

Featureforward()include()
PurposeTransfer control to another servlet for complete responseInclude another servlet's response in current response
Responsible servletForwardedServlet (S-2) provides complete responseIncludingServlet (S-1) is responsible for response
Call frequencyOnly once, mostly as the last statementAny number of times, no restrictions
Response controlSecondServlet has complete control on response objectIncludingServlet (S-1) has complete control
After commitNot allowed (throws IllegalStateException)Allowed
Use caseServlets — processing logic (e.g., validate then forward to inbox)JSPs — presentation logic (e.g., include header/footer)

Forward vs sendRedirect Comparison

Featureforward()sendRedirect()
SideServer-side — client unaware of which servlet provides responseClient-side — client aware of which servlet provides response
ScopeWorks only within the serverWorks within or outside the server
Request objectSame request object forwarded — information sharing via request-scoped attributesNew request object created — no information sharing
NetworkNo extra trip to client — no network traffic or performance issuesExtra trip to client — increases network traffic and performance issues
Implementationrd.forward(req, resp)resp.sendRedirect("url")
Best forCommunicating within the serverCommunicating outside the server
📝 Key Takeaways
  • Forward: server-side, one servlet transfers control to another
  • Include: embed another servlet's response in the current response
  • Request attributes for sharing data between servlets
  • Exam-style questions at the end

🧠 Test Your Knowledge

4 Questions
Progress: 0 / 4

Finished this lesson?

Mark it as complete to track your progress and see technology completion stats.