RequestDispatcher.forward() (vs) HttpServletResponse.sendRedirect() - Yash-777/SteamingServlet GitHub Wiki
A RequestDispatcher forward() is used to forward the same request to another resource whereas ServletResponse sendRedirect() is a two step process. In sendRedirect(), web application returns the response to client with status code 302 (redirect) with URL to send the request.
// 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);
Diagram of a double POST problem encountered in user agents. | Diagram of the double POST problem above being solved by PRG. |
---|---|
forword forwards the request in the Same server like http://help.github.com to https://help.github.com
|
sendRedirect can transfer control from http://java.sun.com to http://www.oracle.com but forward cannot do this. |
* http://help.github.com * https://community.microstrategy.com |
* http://java.sun.com/.../HttpServletResponse.html * http://java.sun.com/../RequestDispatcher.html |
sendRedirect() method redirects the response to another resource. This method actually makes the client(browser) to create a new request to get to the resource. The client can see the new url in the browser.
sendRedirect() accepts relative URL, so it can go for resources inside or outside the server.
sendRedirect() and Request Dispatcher
The main difference between a redirection and a request dispatching is that, redirection makes the client(browser) create a new request to get to the resource, the user can see the new URL while request dispatch get the resource in same request and URL does not changes.
For example, sendRedirect can transfer control from java.sun.com
to http://anydomain.com
but forward cannot do this.
Also, another very important difference is that, sendRedirect() works on response object while request dispatch work on request object.
Example demonstrating usage of sendRedirect()
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
response.sendRedirect("http:/ /www.studytonight.com");
}finally {
out.close();
}
}
}