Showing posts with label ServletRequest. Show all posts
Showing posts with label ServletRequest. Show all posts

Difference between getRequestDispatcher method of the ServletRequest interface and that of the ServletContext interface?

RequestDispatcher getRequestDispatcher(String path) - the same method belongs to both the ServletRequest interface and the ServletContext interface. This method returns a RequestDispatcher object for the resource (dynamic or static) located at the given path. We can use this RequestDispatcher object to forward a request to the resource or to include the resource in a response.

Difference between the two getRequestDispatcher methods

The difference between ServletRequest.getRequestDispatcher(String path) and ServletContext.getRequestDispatcher(String path) is that the former can accept a relative path as well whereas the latter can accept paths relative to the current context root only.

If the path starts with a '/' in the getRequestDispatcher(String path) of the ServletRequest interface then it's interpreted as being relative to the current context root otherwise it'll be a relative to the request of the calling servlet. Whereas, the path of the getRequestDispatcher(String path) of the ServletContext interface must start with '/' only - being relative to the current context root.

Another difference between the two is that path of the getRequestDispatche(String path) of the ServletRequest interface cannot extend outside the current servlet context whereas getRequestDispatcher(String path) of the ServletContext can use the getContext(String uripath) method
to obtain RequestDispatcher for resources in foreign contexts.