RequestDispatcher in Servlet

As of now, we have discussed ServletRequest and ServletResponse Interface in Servlet. We have also discussed how the request is done and how the response is done, their methods, etc. In this article, we will discussĀ  RequestDispatcher Interface in a servlet, their methods, etc.

What is RequestDispatcher?

RequestDispatcher is an interface that defines an object in the servlet that receives a request from the client and sends it to any resources such as JSP, HTML, or any servlet on the server. The serverlet container is responsible for making the object of RequestDispatcher.

public interface RequestDispatcher

Methods in RequestDispatcher

  • public void forward(ServletRequest req,ServletResponse res):This method forward the request from one servlet to any another servlet,JSP,HTML,etc.
    • req: It is a request from a client.
    • res: It is a response to the client.
  • public void include(ServletRequest req, ServletResponse res): This method includes the content of the resource in the response.

How to get Object of RequestDispatcher?

The getRequestDispatcher() method is used to get the object of RequestDispatcher.

RequestDispatcher rd=request.getRequestDispatcher("welcome.html")

After this, we will call forward() or include() method as per our requirement.


Let’s see the example of RequestDispatcher Interface in servlet

In this example, we will verify the login of the user. If the login information is correct it will forward it to the welcome page. otherwise, it will show an error message. The following diagram shows the actual representation of what we are gonna do.