Category: java
Request dispatcher forward and include
Published on 30 Sep 2026
Explanation
RequestDispatcher allows a servlet to transfer a request to another resource such as another servlet, JSP, or HTML page.
Code:
RequestDispatcher dispatcher =
request.getRequestDispatcher("home.jsp");
Explanation
forward() transfers request processing to another resource. The browser URL normally remains unchanged.
Code:
RequestDispatcher dispatcher =
request.getRequestDispatcher("home.jsp");
dispatcher.forward(request, response);
Explanation
include() includes the output of another resource in the current response.
Code:
RequestDispatcher dispatcher =
request.getRequestDispatcher("header.jsp");
dispatcher.include(request, response);
Explanation
Forward is commonly used by a controller servlet to send data to a JSP view.
Code:
request.setAttribute("user", user);
RequestDispatcher dispatcher =
request.getRequestDispatcher("profile.jsp");
dispatcher.forward(request, response);
Explanation
Include is useful when common page sections such as headers, menus, and footers need to be reused.
Code:
out.println("<html>");
request.getRequestDispatcher("header.jsp")
.include(request, response);
out.println("<main>Content</main>");
request.getRequestDispatcher("footer.jsp")
.include(request, response);