RequestDispatcher

tutorial and example
tutorial and example

RequestDispacther is an interface used to receive requests from the users and bind it with other files such as HTML file, Servlet file, JSP file etc. Servlet container is responsible to create RequestDispatcher object.

RequestDispacther provides forward() and include() methods. These methods are used to call RequestDispacther.

Methods of RequestDispatcher

                  Method

            Description

void forward(ServletRequest req, ServletResponse res)

If this method is invoked then the request of current file is send forward to the another file of any type such as HTML, Servlet, JSP etc. and the response of that file is provided by the server.

void include(ServletRequest req, ServletResponse res)

If this method is invoked then the content of current file such as HTML, Servlet, JSP is included with the response.

Example of RequestDispatcher interface

In this example we create a form in html file. ServletChecker.java file checks the password field of that form. If the entered password length is less than 8 then include() method is invoked and generates error else forward() method is invoked and forward that request to another java file.

index.html

ServletChecker.java

ServletForward.java

Output:

Now we have to fill up this form.

The inserted length of the password is less than 8 character. So it will generate error message and include the current form within it.

As expected error message generated.

Now inserted length of the form is greater than 8 character. So forward() method is invoked and sent as a request to another page.

The following response generated.