Request Dispatcher in Java Servlets
RequestDispatcher allows one Servlet to delegate processing to another Servlet or JSP on the server side, without the client knowing about the internal transfer.
forward() vs include()
forward()
Transfers control completely. The original Servlet stops processing. Browser URL stays the same. Used for MVC controller → view pattern.
include()
Embeds another resource's output into the current response. Original Servlet continues after include returns. Used for headers, footers, sidebars.
Forward Example
@WebServlet("/dashboard")
public class DashboardServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
req.setAttribute("stats", loadStats());
req.getRequestDispatcher("/WEB-INF/views/dashboard.jsp")
.forward(req, resp);
}
}When to Use sendRedirect Instead
Use sendRedirect() when you want the browser URL to change (after POST to prevent duplicate submissions) or when redirecting to an external site. Use forward() when keeping the same URL and performing server-side view rendering.
Frequently Asked Questions
Can I forward to an external URL?▼
No. RequestDispatcher only works for resources within the same web application context. Use sendRedirect() for external URLs.
