The RequestDispatcher is a Servlet API tool that lets you forward or include one web resource (like a servlet, JSP, or static file) from another servlet.
📦 What is RequestDispatcher?
It’s an interface in the javax.servlet package that allows one servlet to:
| Action | Description |
|---|---|
| Forward | Transfer the request to another resource on the server, without the client knowing. |
| Include | Include the output of another resource in the current response. |
RequestDispatcher dispatcher = request.getRequestDispatcher("target.jsp");
Or via the ServletContext:
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/target.jsp");
🔁 Two Main Operations
1. Forward
Transfers control to another resource on the server, and terminates the current servlet.
request.getRequestDispatcher("/result.jsp").forward(request, response);
- URL does not change in the browser
- Request and response objects are shared
- Control does not return to the original servlet
➡️ Use case: Pass control after processing form data, like login or registration
2. Include
Includes the output of another resource into the current response.
request.getRequestDispatcher("/footer.jsp").include(request, response);
- Merges output
- Used for layouts, header/footer, etc.
- Original servlet keeps control
➡️ Use case: Composing pages with common headers/footers
🧪 Example: Forwarding to a JSP
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
String name = req.getParameter("name");
req.setAttribute("user", name); // pass data
RequestDispatcher dispatcher = req.getRequestDispatcher("/welcome.jsp");
dispatcher.forward(req, res); // internally transfer
}
In welcome.jsp:
<h1>Welcome, ${user}</h1>
🧠 RequestDispatcher vs Redirect
| Feature | RequestDispatcher.forward() | HttpServletResponse.sendRedirect() |
|---|---|---|
| Type | Server-side | Client-side |
| Browser URL changes? | ❌ No | ✅ Yes |
| Can share request data? | ✅ Yes (setAttribute) | ❌ No (requires session or params) |
| Control returns? | ❌ No (after forward) | ❌ No (new request entirely) |
| Use case | Internal workflow | Redirecting user elsewhere (e.g., login) |
✅ Summary
| Concept | Description |
|---|---|
| What is it? | Interface to forward or include resources |
| Where to get it? | request.getRequestDispatcher() or from context |
| Key methods | forward(), include() |
| Use cases | Layouts, controller-to-view transitions |