JavaResp JavaResp - 6 months ago 34
Java Question

ServletContext.getRequestDispatcher() vs ServletRequest.getRequestDispatcher()

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

Answer

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.