Java.Servlet.What is the difference between sendRedirect() and forward()?

Featureforward() (RequestDispatcher)sendRedirect() (HttpServletResponse)
Who handles itServerBrowser (client)
How it worksServer 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 requestNo, because a new request is made (attributes are lost unless passed as URL params)
Use case exampleForwarding to an error page, controller dispatching internallyRedirecting after a POST to avoid resubmission (Post-Redirect-Get pattern)
PerformanceFaster (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.
This entry was posted in Без рубрики. Bookmark the permalink.