Methods | Description |
---|---|
public void forward(ServletRequest request, ServletResponse response) | It forwards a client request from a servlet to another resource (servlet, JSP file, HTML file) on the server. |
public void include(ServletRequest request, ServletResponse response) | Includes the content of a resource (Servlet, JSP pages, HTML file) in the response. |
RequestDispatcher rd = request.getRequestDispatcher("index.html");
rd.forward(request, response);
OR
RequestDispatcher rd = request.getRequestDispatcher("index.html");
rd.include(request, response);
forward( ) | sendRedirect( ) |
---|---|
Used to forward the resources available within the server. | Used to redirect the resources to different servers or domains. |
The forward( ) method is executed on the server side. | The sentRedirect( ) method is executed on the client side. |
The forward( ) method is faster than sendRedirect( ). | It is slower because each time a new request is created, old one is lost. |
The transfer of control is done by container and client/browser is not involved. | The transfer of control is assigned to the browser and a new request to the given URL is initiated. |
The request is shared by the target resource. | New request is created for the server resource. |
It is declared in RequestDispatcher interface. | It is declared in HttpServletResponse. |
//SendRedirectDemo.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class SendRedirectDemo extends HttpServlet
{
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
response.sendRedirect("http://tutorialride.com/")
pw.close();
}
}