Thursday, January 6, 2011

Servlet & RequestDispatcher

This a basic post on Servlet and RequestDispatcher API of Servlet.

Servlet is provided with an api “RequestDispatcher” which can be used to forward request to another resource on web container.

RequestDispatcher can be obtained in two ways: either from Request or from ServletContext.

The RequestDispather obtained from request can be used to point or forward to resources on same web application.

Eg:
public void doGet(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException {

  RequestDispatcher rd = request.getRequestDispatcher("servletB");
  rd.forward(request, response);

In Contrast, RequestDispather Obtained from ServletContext can point to or forward to resources on the web container.

Eg:
public void doGet(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {

   RequestDispatcher rd = getServletContext().getContext("WebAppB").getRequestDispatcher("servletB");
   rd.forward(request, response);

No comments:

Post a Comment