What's the difference between RequestDispatcher.forward() and HttpServletResponse.sendRedirect()?

Raj picture Raj · Aug 28, 2011 · Viewed 49k times · Source

What is the difference between RequestDispatcher's forward() and HttpServletResponse's sendRedirect() method?
Can anyone explain with a example and best usage of these methods with a real time example?

Answer

dov.amir picture dov.amir · Aug 28, 2011

Redirection is a type of response sent back to the client, whereas the forward delegation takes place completely on the server side and the result of the forward action returns to the client as if it came only from the original URL.

Another difference is that forward delegation can be used only for in-applications resources, whereas redirection command can redirect the client browser outside the current domain.

Examples:

// Sends a temporary redirect to the HTTP client. Only absolute URLs are allowed.
ServletResponse.sendRedirect(String location);


// Delegates one HttpRequest to another dynamic or static resource
HttpRequest.getRequestDispatcher("example.jsp").forward(request, response);


// Includes/enriches current response with another dynamic or static resource
HttpRequest.getRequestDispatcher("example.html").include(request, response);


Another good explanation can be found here:
Difference between sendRedirect() and forward()