Java Academy

Master Java Development

Menu

Core Java

Servlets

JDBC

Microservices

Build Tools

APIs

Servlets · Lesson 7

RequestDispatcher (Forward vs Redirect)

Routing a Request

RequestDispatcher transfers control inside the same web application. A forward keeps the original request and response, while a redirect tells the browser to make a new request to another URL. The choice affects the address bar, request attributes, and whether a page refresh repeats a submission.

Forwarding with RequestDispatcher

Use forward when a servlet prepares data for a server-side view. Request attributes are available to the target resource because the request remains the same.

import jakarta.servlet.RequestDispatcher;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;

public class ProfileServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setAttribute("displayName", "Aisha Rahman");
        RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/views/profile.jsp");
        dispatcher.forward(request, response);
    }
}

Forward Versus Redirect

AspectForwardRedirect
Browser request countOneUsually two
Address barOriginal URLNew URL
Request attributesPreservedLost unless encoded or stored elsewhere
Cross-application targetNoYes
Best useRender a server-side viewFinish a command or change location

Common Mistake and Practices

Common Mistake: Forwarding after a successful POST and then refreshing the page. The browser may submit the form again; use redirect after a state-changing operation with the Post/Redirect/Get pattern.

  • Use forward for internal view rendering.
  • Use sendRedirect for a new browser location.
  • Keep JSP files under WEB-INF when they should not be requested directly.
  • Do not write a response before forwarding or redirecting.
  • Preserve one-time messages through a deliberate mechanism.

Real-World Use Case

A checkout servlet validates an order, saves it, and redirects to /orders/123 so refreshing the confirmation page does not submit payment again. A GET servlet forwards to a protected JSP to render the order details.

Quiz Check

Quick Knowledge Test

Loading quiz questions...