The RequestDispatcher interface present in javax.servlet.* package which is used to dispatch the request to another resource. The resource may be html, Servlet or jsp. This interface can also be used to include the content of another resource also. Actually this is Servlet Collaboration. There are two methods defined in the RequestDispatcher interface, such as forward() method and include() method.
The forward() method is used to forward a request from a Servlet to another resource(resource may be html, jsp file or Servlet) on the server.
public void forward(ServletRequest request, ServletResponse response)throws ServletException,java.io.IOException:
this forward() method takes two arguments such as request object and response object and throws ServletException and IOException.
The include() method is used to include the contents of a resource in the response.
public void include(ServletRequest request, ServletResponse response)throws ServletException, java.io.IOException: here also this method takes request object and response object and throws ServletException, IOException.
These forward() method and include() method is invoked by the RequestDispatcher object. So here the question arises how we will get the RequestDispatcher object. The answer is very simple. There is a method getRequestDispatcher() present in ServletRequest interface when invoked by the request object then it returns RequestDispatcher object.
Let's see an example for better clarity:
In this example, we are validating a password entered by the user. If password is javarace, it will forward the request to the MyServlet2, otherwise it will show an error message: invalid password... In this example, we have considered following files:
login.html: for getting input from the user.
First.java: a Servlet class for processing the response. If password is javarace, it will forward the request to the welcome Servlet.
Welcome.java file: a Servlet class for displaying the welcome message.
web.xml file: a deployment descriptor file that contains the information about the Servlet.