Feature | forward() (RequestDispatcher) | sendRedirect() (HttpServletResponse) |
---|---|---|
Who handles it | Server | Browser (client) |
How it works | Server internally forwards the same request to another resource (another servlet, JSP, HTML, etc.) | Server tells browser: “Hey, go make a new request to a different URL!” |
Browser URL changes? | No (URL stays the same) | Yes (URL changes to the new target) |
New request? | No (same request and response objects continue) | Yes (new request from browser) |
Can pass request attributes? | Yes, because it’s the same request | No, because a new request is made (attributes are lost unless passed as URL params) |
Use case example | Forwarding to an error page, controller dispatching internally | Redirecting after a POST to avoid resubmission (Post-Redirect-Get pattern) |
Performance | Faster (no network roundtrip) | Slower (extra network call) |
In short:
forward()
- Happens inside the server.
- Invisible to the browser.
- Request is preserved (attributes stay).
- More efficient because no second HTTP request.
sendRedirect()
- Browser is told to go to a new URL.
- New HTTP request.
- Slower, but useful if you want the user to know they are on a different page.
- Useful if you want fresh start without carrying old request attributes.
Code Example:
✅ Forward:
RequestDispatcher dispatcher = request.getRequestDispatcher("/dashboard");
dispatcher.forward(request, response);
URL stays the same.
Dashboard is generated using the original request.
✅ Redirect:
response.sendRedirect(request.getContextPath() + "/dashboard");
Browser URL changes to /dashboard
.
New request is made by the browser.
A small real-life scenario:
- Forward:
- User submits login form.
- Server forwards internally to a dashboard page because the user is authenticated.
- Redirect:
- After user logs out, you redirect them to login page.
- This way if they press Refresh after logout, it won’t re-execute old logout code again.