In Java web applications, navigating between servlets can be accomplished through two primary mechanisms: request forwarding and response redirection. Understanding the distintcion between thece approaches is fundamental to building robust servlet-based applications.
Request Forwarding with RequestDispatcher
Request forwarding utilizes the RequestDispatcher interface to transfer control to another resource within the same application while maintaining the original request and response objects. This allows data stored in the request scope to be accessed by the target servlet.
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
req.setAttribute("username", "Michael Jordan");
req.getRequestDispatcher("/ProfileController")
.forward(req, resp);
}
}
</div><div>```
public class ProfileController extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String username = (String) req.getAttribute("username");
resp.setContentType("text/html;charset=UTF-8");
resp.getWriter().print("Welcome, " + username);
}
}
- The browser URL remains unchanged
- Both servlets share the same request and response objects
- Attributes stored in the request are accessible to the forwarded servlet
- Forwards occur entirely on the server side
Response Redirection with sendRedirect
Response redirection instructs the client browser to issue a new HTTP request to the specified URL. Unlike forwarding, this creates a completely separate request cycle.
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.sendRedirect(req.getContextPath() + "/dashboard");
}
}
</div><div>```
public class DashboardController extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setContentType("text/html;charset=UTF-8");
resp.getWriter().write("Dashboard Loaded");
}
}
- The browser URL updates to reflect the new location
- A new HTTP request is created, meaning request attributes are lost
- The redirection target can be an external URL
- Two separate request-response cycles occur
Comparison Summary
| Aspect | Request Forward | Response Redirect |
|---|---|---|
| URL in Browser | Original URL unchanged | Changes to new URL |
| Request Object | Shared between servlets | New request created |
| Request Attributes | Preserved | Lost |
| Server Load | Single request cycle | Two request cycles |
| External URLs | Not supported | Supported |
Choose request forwarding when you need to pass data betwean components, and use response redirection when you want the client to be aware of the navigation change or when redirecting to external resources.