Request Dispatcher


#1

What is request dispatcher?


#2

RequestDispatcher interface is used to forward the request to another resource that can be HTML, JSP or another servlet in same application. We can also use this to include the content of another resource to the response. This interface is used for inter-servlet communication in the same context.

There are two methods defined in this interface:

void forward(ServletRequest request, ServletResponse response) – forwards the request from a servlet to another resource (servlet, JSP file, or HTML file) on the server.
void include(ServletRequest request, ServletResponse response) – includes the content of a resource (servlet, JSP page, HTML file) in the response.


#3

Request Dispatcher:

The request dispatcher interface provides the facility of dispatching the request to another resource it may be html,servlet or jsp.this interface can also be used to include the content of another resource also.it is one of the way of servlet collaboration.

There are two methods defined in the requestdispatcher interface:

1)Public void forward: forwards a request from a servlet to another resource (servlet,jsp file or HTML file) on the server.

2)Public void include: includes the content of a resource(servlet,JSP page or HTML file) in the response.

The getRequestDispatcher() method of the servletRequest interface returns the object of RequestDispatcher.syntax.

syntax: RequestDispatcher getRequestDis

Example of RequestDispatcher interface:

in this example,we are validating the password entered by the user.if password is servlet,it will forward the request to the Welcomeservlet,otherwise will show an error message:sorry username or password error!in this programme we are searching for hardcored information.but you can check it to the database also .in this example we have created the following files:

  • index.html file : for getting input from the user.
  • login.java file : a servlet class for processing the response if password is servlet ,it will forward the request to the welcome servlet.
  • welcomeservlet.java file : a servlet class for displaying the welcome message.
  • web.xml file : a deployment descriptor file that contains the information about the servlet.