Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ServletContext.getRequestDispatcher() vs ServletRequest.getRequestDispatcher()

Tags:

why

getRequestDispatcher(String path) of the ServletRequest interface cannot extend outside the current servlet context

where as

getRequestDispatcher(String path) of the ServletContext can use the getContext(String uripath) method to obtain RequestDispatcher for resources in foreign contexts.

and how??

Please help

like image 692
JavaResp Avatar asked Sep 11 '09 14:09

JavaResp


People also ask

Why are the request getRequestDispatcher () used?

getRequestDispatcher. Returns a RequestDispatcher object that acts as a wrapper for the resource located at the given path. A RequestDispatcher object can be used to forward a request to the resource or to include the resource in a response. The resource can be dynamic or static.

Which of the following are correct statements about the getRequestDispatcher () method?

getRequestDispatcher(String URL) is found in both ServletContext and HttpServletRequest, hence C is correct. The include method defined in the RequestDispatcher class can be invoked even if response has been committed (unlike forward).

What is Getservletcontext in Java?

Interface ServletContext. public interface ServletContext. Defines a set of methods that a servlet uses to communicate with its servlet container, for example, to get the MIME type of a file, dispatch requests, or write to a log file. There is one context per "web application" per Java Virtual Machine.


2 Answers

If you use an absolute path such as ("/index.jsp"), there is no difference.

If you use relative path, you must use HttpServletRequest.getRequestDispatcher(). ServletContext.getRequestDispatcher() doesn't allow it.

For example, if you receive your request on http://example.com/myapp/subdir,

    RequestDispatcher dispatcher =          request.getRequestDispatcher("index.jsp");     dispatcher.forward( request, response );  

Will forward the request to the page http://example.com/myapp/subdir/index.jsp.

In any case, you can't forward request to a resource outside of the context.

like image 133
ZZ Coder Avatar answered Sep 28 '22 17:09

ZZ Coder


The request method getRequestDispatcher() can be used for referring to local servlets within single webapp.

Servlet context based getRequestDispatcher() method can used of referring servlets from other web applications deployed on SAME server.

like image 44
shraddha Avatar answered Sep 28 '22 16:09

shraddha