Way2Java

RequestDispatcher from ServletRequest vs ServletContext

We have seen two programs with include() and forward() methods of RequestDispatcher. In both the programs, getRequestDispatcher(String path) of ServletRequest is used to obtain an object of RequestDispatcher. Infact, RequestDispatcher object can be obtained in another way also – using javax.servlet.ServletContext. The same getRequestDispatcher(String path) method exist in ServletContext also. That is, the same method getRequestDispatcher(String path) exists in both the interfaces of ServletRequest and ServletContext. The method returns an object of RequestDispatcher.

Let us see the signature as defined in API of ServletRequest:

Signature as defined in API of ServletContext:

Following table gives the differences of using getRequestDispatcher(String path) method to obtain an object of RequestDispatcher.

Property ServletRequest ServletContext
Context Cannot work outside the present Servlet context. Capable to use foreign Servlet context also. Can use getContext() to obtain RequestDispatcher of other contexts.
Access Location getRequestDispatcher() of ServletRequest is useful to refer the servlets available in the same Web application. getRequestDispatcher() of ServletContext is useful to refer servlets available on other Web applications on different Web server also.
Scope Stored in page level. Scope is application level.
Relative position request.getRequestDispatcher("url") means the dispatch is relative to the current HTTP request. That is, it locates the resource relative to the request path getServletContext().getRequestDispatcher("url") means the dispatch is relative to the root of the current context.
Accessibility Used to call a Servlet or JSP within the current application available, that too, on the same Web server. Used to call a Servlet or JSP exiting on another Web server.
Example Code request.getRequestDispatcher("/S2"); where S2 is the alias name of the Servlet available on the same server and on the same Web application. getServletContext().getRequestDispatcher("/india/S2"); where india is the current context root(in all our earlier Servlet programs).

=============For Extra Reading on related Topics===============

  1. 20 difference between forward and sendRedirect
  2. 16 differences between include and forward
  3. 12 Differences – GET vs POST – Which to prefer?