tags:

views:

144

answers:

2

HI I like to know there is a single method called getRequestDispatcher() in ServletRequest and ServletContext interfaces. What is the difference?

+2  A: 

As stated in the Servlet API Javadocs,

The difference between this method [the ServletRequest one] and ServletContext.getRequestDispatcher(java.lang.String) is that this method can take a relative path.

Tim Yates
Personally, I prefer to link to the docs in the JavaEE specification, but the copy there says the same thing: http://java.sun.com/javaee/5/docs/api/javax/servlet/ServletRequest.html#getRequestDispatcher%28java.lang.String%29
R. Bemrose
A: 

You can pass a relative path to getRequestDispatcher() of ServletRequest but not to getRequestDispatcher() of ServletContext.

Example:

My current request is served from page - webapp/view/core/bar.jsp and requested page - webapp/view/util/foo.jsp

request.getRequestDispatcher("../util/foo.jsp") is valid and will be evaluated to the path relative to current request.

servletContext.getRequestDispatcher("/view/util/foo.jsp") is valid and will evaluate from context root.

This is because ServletContext will not be aware of current request path. If you decide to use '/' root to access your resources, then both ways are same.

Joseph Kulandai