Thursday, October 27, 2005

What’s the difference between ServletContext.getRequestDispatcher("/ResourceName") and ServletRequest.getRequestDispatcher("/ResourceName").

Explain relative path and absolute path.

With ServletRequest.getRequestDispatcher("/ResourceName") you can specify a relative path.

Relative path means it starts from the root of that particular web application

RequestDispatchers work relative to the context root

for example in Tomcat:

your application directory tomcat/webapps/my-app
your jsp page webapps/my-app/example.jsp
Relative path
/example.jsp means my-app/example.jsp



You don’t need to include the forward slash in ServletRequest whereas you need to include a forward slash in ServletContext. You cannot specify a path relative to current resource in ServletContext.


Excerpt from Context.getRequestDispatcher() method.

The pathname must begin with a "/" and is interpreted as relative to the current context root.

Excerpt from Request.getRequestDispatcher() method.

The pathname specified may be relative, although it cannot extend outside the current servlet context.

ServletRequest.getRequestDispathcher() takes relative path.

ServletContext.getRequestDispathcher() and

HttpServletResponse.sendRedirect() takes absolute paths i.e. paths starting with "/" which is taken as relative to context root of the current web-app.

If there is no initial forward slash then it is a relative path.

If a slash is present then it is considered relative to the current context root.

Absolute path:

The complete URL location needed to locate the page/file




Post a Comment

<< Home