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
| Aspect | Forward | Redirect |
|---|---|---|
| Browser request count | One | Usually two |
| Address bar | Original URL | New URL |
| Request attributes | Preserved | Lost unless encoded or stored elsewhere |
| Cross-application target | No | Yes |
| Best use | Render a server-side view | Finish 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
forwardfor internal view rendering. - Use
sendRedirectfor a new browser location. - Keep JSP files under
WEB-INFwhen 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