Servlet Collaboration in Java: RequestDispatcher vs sendRedirect
Servlet Collaboration means how one servlet communicates with another servlet and passes data between them. It is a core concept in Java web development, because real applications rarely use a single servlet for everything.
In this guide, you will learn the two ways to achieve Servlet Collaboration —
RequestDispatcher (using include() and
forward()) and sendRedirect() — with complete runnable
examples, output screenshots, and the key differences between them.
What is Servlet Collaboration?
Servlet Collaboration is the mechanism by which one servlet communicates with another servlet and passes information or data between them. This is useful when you want to split responsibilities across servlets — for example, one servlet validates input while another handles the response.
There are two ways to achieve Servlet Collaboration:
- Using the RequestDispatcher interface — server-side forwarding
- Using the sendRedirect() method — client-side redirection
1. RequestDispatcher Interface
Key facts about the RequestDispatcher interface:
-
RequestDispatcheris an interface in thejavax.servletpackage. -
You get an instance of
RequestDispatcherfrom theHttpServletRequestobject:RequestDispatcher rd = request.getRequestDispatcher("/pageName"); - No new request is created when forwarding to another page. The same request and response objects are reused.
-
RequestDispatcheris used to call pages within the same project (internal resources only). -
It has two methods:
include(request, response)forward(request, response)
-
include()adds the target page's output to the current servlet's response — both outputs appear in the final response. -
forward()transfers control completely to the target page — the current servlet's output is not included. -
RequestScope, SessionScope, and ApplicationScope are all applicable
with
RequestDispatcher. - All processing is done at the server side — the browser is not aware that a forward happened.
RequestDispatcher — Example
Below is the flow diagram for the RequestDispatcher example:
FirstPage.java
This servlet reads the name parameter. If empty, it uses
include() to show the form again. Otherwise, it uses forward()
to pass control to SecondPage.
package com.deepsingh44.controller;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/first")
public class FirstPage extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doProcess(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doProcess(req, resp);
}
private void doProcess(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String name = req.getParameter("name");
if (name.isEmpty()) {
resp.getWriter().print("Please enter name");
req.getRequestDispatcher("index.html").include(req, resp);
} else {
req.setAttribute("name", name);
req.getRequestDispatcher("second").forward(req, resp);
}
}
}
SecondPage.java
This servlet reads the name attribute set by FirstPage and
prints a welcome message. Since forward() uses the same request object,
the attribute is available.
package com.deepsingh44.controller;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/second")
public class SecondPage extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doProcess(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doProcess(req, resp);
}
private void doProcess(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String name = req.getAttribute("name").toString();
resp.getWriter().print("Welcome, " + name);
}
}
index.html
<form action="first">
<p>
Enter Name: <input type="text" name="name">
</p>
<p>
<input type="submit" value="submit">
</p>
</form>
RequestDispatcher — Output
Below are the output screenshots for the RequestDispatcher example:
2. sendRedirect() Method
Key facts about the sendRedirect() method:
-
sendRedirect()is a method of theHttpServletResponseobject. -
With
sendRedirect(), a new request is always created — the browser issues a fresh request to the target URL. - It can redirect to both internal pages (within the same app) and external URLs (e.g., google.com).
-
RequestScope is NOT applicable with
sendRedirect()— the original request is discarded. - Only SessionScope and ApplicationScope are applicable — because those live outside the request lifecycle.
- Processing happens at the client side — the browser receives a 302 status and makes a new request.
sendRedirect() — Example
Below is the flow diagram for the sendRedirect example:
FirstPage.java
Instead of using request scope, this version stores the name in
ServletContext (application scope), because request scope is lost after
redirect.
package com.deepsingh44.controller;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/first")
public class FirstPage extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doProcess(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doProcess(req, resp);
}
private void doProcess(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setContentType("text/html");
String name = req.getParameter("name");
if (name.isEmpty()) {
resp.getWriter().print("Please enter name");
req.getRequestDispatcher("index.html").include(req, resp);
} else {
req.getServletContext().setAttribute("name", name);
resp.sendRedirect("second");
}
}
}
SecondPage.java
This servlet reads name from ServletContext (application
scope) — which is the only scope that survives a redirect.
package com.deepsingh44.controller;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/second")
public class SecondPage extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doProcess(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doProcess(req, resp);
}
private void doProcess(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String name = req.getServletContext().getAttribute("name").toString();
resp.getWriter().print("Welcome, " + name);
}
}
index.html
<form action="first">
<p>
Enter Name: <input type="text" name="name">
</p>
<p>
<input type="submit" value="submit">
</p>
</form>
sendRedirect() — Output
Below are the output screenshots for the sendRedirect example:
RequestDispatcher vs sendRedirect Comparison
| Feature | RequestDispatcher | sendRedirect() |
|---|---|---|
| New request created? | No | Yes |
| Can call external URLs? | No (same project only) | Yes |
| RequestScope available? | Yes | No |
| SessionScope available? | Yes | Yes |
| ApplicationScope available? | Yes | Yes |
| Processing side | Server side | Client side |
| URL in browser changes? | No | Yes |
| Typical use case | MVC view forwarding | Post-Redirect-Get pattern |
Frequently Asked Questions
What is Servlet Collaboration in Java?
Servlet Collaboration means how one servlet communicates with another servlet and passes
data between them. It is achieved in two ways: using the RequestDispatcher
interface (include and forward methods) or using the
HttpServletResponse.sendRedirect() method.
What is the difference between forward() and include() in RequestDispatcher?
forward() transfers control completely to the target resource — the current
servlet's output is discarded. include() adds the target resource's output
to the current servlet's response — both outputs are combined in the final response.
What is the difference between RequestDispatcher and sendRedirect()?
RequestDispatcher forwards within the same application, no new request is
created, and request scope attributes are preserved. sendRedirect() sends a
302 response to the client, which then makes a new request to the target URL — so
request scope is lost. sendRedirect() can also redirect to external URLs.
Which scopes are available in RequestDispatcher and sendRedirect?
RequestDispatcher supports RequestScope, SessionScope, and ApplicationScope.
sendRedirect() only supports SessionScope and ApplicationScope —
RequestScope is not available because the original request object is discarded after the
redirect.
Is processing done on the client side or server side?
RequestDispatcher performs all forwarding on the server side
— the browser is not aware of it. sendRedirect() performs the redirect on
the client side — the browser receives the 302 response and issues a
brand new request to the target URL.
Conclusion
Servlet Collaboration lets multiple servlets work together to handle a single user request. You learned the two approaches — RequestDispatcher (server-side, no new request, supports request scope) and sendRedirect() (client-side, new request, only session/application scope).
Choose RequestDispatcher when you want MVC-style view forwarding with shared
request data. Choose sendRedirect() when you want a fresh URL, need to
redirect to an external site, or are implementing the Post-Redirect-Get pattern to avoid
form resubmission.
Related topics: Servlet Life Cycle, HttpSession in Servlet, Servlet Filters, JSP with Servlet, MVC Pattern in Java Web Apps, ServletContext vs ServletConfig
No comments:
Post a Comment