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
JCode Cell
1 
2import javax.servlet.*;
3import javax.servlet.http.*;
4import java.io.*;
5import javax.servlet.annotation.*;
6@WebServlet("/test1")
7public class FirstServlet extends HttpServlet
8{
9public void doGet(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException
10{
11PrintWriter out=resp.getWriter();
12out.println("<h1>This is First Servlet</h1>");
13RequestDispatcher rd = req.getRequestDispatcher("/test2");
14rd.forward(req,resp);
15}
16}
17
Output

<h1>This is First Servlet</h1>
      

SecondServlet.java

Example03
JCode Cell
1 
2import javax.servlet.*;
3import javax.servlet.http.*;
4import java.io.*;
5import javax.servlet.annotation.*;
6@WebServlet("/test2")
7public class SecondServlet extends HttpServlet
8{
9 
10public void doGet(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException
11{
12PrintWriter out=resp.getWriter();
13out.println("<h1>This is Second Servlet</h1>");
14 
15}
16}
17
Output

<h1>This is Second Servlet</h1>
      

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
JCode Cell
1 
2<h1> This is forward demo</h1>
3<form action = "/advapps3D/test1" >
4Enter Name :<input type=text name=uname><br>
5Enter Password :<input type=text name=pwd><br>
6<input type=submit>
7</form>
8

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
JCode Cell
1 
2import javax.servlet.*;
3import javax.servlet.http.*;
4import java.io.*;
5import javax.servlet.annotation.*;
6@WebServlet("/test1")
7public class ValidateServlet extends HttpServlet
8{
9public void doGet(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException
10{
11String name = req.getParameter("uname");
12String pwd = req.getParameter("pwd");
13if(name.equals("Durga") && pwd.equals("scwcd"))
14{
15ServletContext context=getServletContext();
16RequestDispatcher rd =context.getRequestDispatcher("/inbox.jsp");
17rd.forward(req,resp);
18}
19else
20{
21RequestDispatcher rd =req.getRequestDispatcher("/error.jsp");
22rd.forward(req,resp);
23}
24 
25}
26}
27

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
JCode Cell
1 
2public class FirstServlet extends HttpServlet
3{
4public void doGet(..)...
5{
6PrintWriter out=resp.getWriter();
7RequestDispatcher rd=req.getRequestDispatcher("/test2");
8rd.forward(req,resp);
9System.out.println("After forward control comes back");// it will printed in the serverconsole
10out.println("Hello this is FirstServlet again");//This line ignored by web container
11System.out.println(10/0);// AE information will be displayed to the end user instead o
12}
13}
14

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
JCode Cell
1 
2import javax.servlet.*;
3import javax.servlet.http.*;
4import java.io.*;
5import java.util.*;
6public class ForwardAttributeDemo extends HttpServlet
7{
8 
9public void doGet(HttpServletRequest req,HttpServletResponse resp) throwsServletException,IOException
10{
11PrintWriter out = resp.getWriter();
12out.println("<h1>Forward Request Attributes</h1>");
13Enumeration e = req.getAttributeNames();
14while(e.hasMoreElements())
15{
16String name= (String)e.nextElement();
17Object value = req.getAttribute(name);
18out.println(name+"....."+value+"<br>");
19}
20}
21}
22

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
JCode Cell
1 
2import javax.servlet.*;
3import javax.servlet.http.*;
4import java.io.*;
5import javax.servlet.annotation.*;
6@WebServlet("/test1")
7public class FirstServlet extends HttpServlet
8{
9public void doGet(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException
10{
11PrintWriter out=resp.getWriter();
12out.println("<h1>Hello This is FirstServlet</h1>");
13RequestDispatcher rd=req.getRequestDispatcher("/test2");
14rd.include(req,resp);
15out.println("<h1>Hi This is First Servlet again</h1>");
16}
17}
18
Output

<h1>Hello This is FirstServlet</h1>
<h1>Hi This is First Servlet again</h1>
      

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
JCode Cell
1 
2import javax.servlet.*;
3import javax.servlet.http.*;
4import java.io.*;
5import javax.servlet.annotation.*;
6@WebServlet("/test")
7public class SecondServlet extends HttpServlet
8{
9public void doGet(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException
10{
11PrintWriter out=resp.getWriter();
12out.println("<h1>This is Second Servlet</h1>");
13}
14}
15
Output

<h1>This is Second Servlet</h1>
      

Foreign RequestDispatcher

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

Example12
JCode Cell
1 
2import javax.servlet.*;
3import javax.servlet.http.*;
4import java.io.*;
5import javax.servlet.annotation.*;
6@WebServlet("/test1")
7public class FirstServlet extends HttpServlet
8{
9public void doGet(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException
10{
11ServletContext context=getServletContext();
12ServletContext fc=context.getContext("/advapps3I");
13 
14RequestDispatcher rd=fc.getRequestDispatcher("/test2");
15rd.forward(req,resp);
16}
17}
18

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
JCode Cell
1 
2import javax.servlet.*;
3import javax.servlet.http.*;
4import java.io.*;
5import javax.servlet.annotation.*;
6@WebServlet("/test2")
7public class SecondServlet extends HttpServlet
8{
9public void doGet(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException
10{
11PrintWriter out=resp.getWriter();
12out.println("<h1>This is Second Servlet..You can access by Foreign Request Dispatcher</h1>");
13}
14}
15
Output

<h1>This is Second Servlet..You can access by Foreign Request Dispatcher</h1>
      

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