We can get RequestDispatcher object either by ServletRequest object or by ServletContext object

By ServletRequest object

public RequestDispatcher getRequestDispatcher(String target)
The target resource path can be specified either by absolute url or relative url.

Example:

    RequestDispatcher rd=req.getRequestDispatcher("/test2");//Absolute
    RequestDispatcher rd=req.getRequestDispatcher("test2");//Relative

If the target resource is not available then we will get 404(status code) response.

By ServletContext

ServletContext interface defines the following methods to get RequestDispatcher object.

  1. public RequestDispatcher getRequestDispatcher(String target)
  2. Here the target resource path should be specified by absolute url only(i.e it should start with ‘/’),Otherwise we will get Runtime Exception saying “IllegalArgumentException”.

    If the target resource is not available then we will get 404 response.

    Example:

            RequestDispatcher rd=context.getRequestDispatcher("/test2");//valid
            RequestDispatcher rd=context.getRequestDispatcher("test2");//IllegalArgumentException
    
  3. public RequestDispatcher getNamedDispatcher(String target)
  4. The argument represents logical name of target Servlet represented by servlet-name tag.
    If the specified Servlet is not available then we will get null.

Difference between RequestDispatcher from ServletRequest and ServletContext
RequestDispatcher from request RequestDispatcher from context
req.getRequestDispatcher(String target) context.getRequestDispatcher(String target)
The target resource path can be specified either by absolute or relative url.(String target) The target resource path should be absolute url ,Otherwise IllegalArgumentException
we can’t get RequestDispatcher by Servlet name. we can get RequestDispatcher even by Servlet name also
Recommended to use for communicating with in the web application Required to use for communicating with outside web application but with in same web container/Server.