Tech and Media Labs
This site uses cookies to improve the user experience.




RequestDispatcher

Jakob Jenkov
Last update: 2014-05-25

The RequestDispatcher class enables your servlet to "call" another servlet from inside another servlet. The other servlet is called as if an HTTP request was sent to it by a browser.

You can obtain a RequestDispatcher from the HttpServletRequest object, like this:

protected void doPost(HttpServletRequest request,
                      HttpServletResponse response)
        throws ServletException, IOException {

  RequestDispatcher requestDispatcher =
    request.getRequestDispatcher("/anotherURL.simple");
}

The above code obtains a RequestDispatcher targeted at whatever Servlet (or JSP) that is mapped to the URL /anotherUrl.simple.

You can call the RequestDispatcher using either its include() or forward() method:

requestDispatcher.forward(request, response);

requestDispatcher.include(request, response);

By calling either the include() or forward() method the servlet container activates whatever Servlet is mapped to the URL the RequestDispatcher.

The activated servlet has access to the same request as the servlet calling it, and will write to the same response as your current servlet. That way you can merge the output of servlets into a single repsonse.

There is a little difference between calling the forward() and include() method.

The forward() method intended for use in forwarding the request, meaning after the response of the calling servlet has been committed. You cannot merge response output using this method.

The include() method merges the response written by the calling servlet, and the activated servlet. This way you can achieve "server side includes" using the include().

Personally, I mostly use the include() method.

Jakob Jenkov




Copyright  Jenkov Aps
Close TOC