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

Code:

ServletRequest.getRequestDispatcher("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.

ServletContext.getRequestDispatcher("/example.jsp");

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.
ServletRequest.getRequestDispatcher("example.jsp");

If a slash is present then it is considered relative to the current context root.
ServletContext.getRequestDispatcher("/example.jsp");

Absolute path:

The complete URL location needed to locate the page/file

response.sendredirect(http://myServer.com/development/jsp/homepage.jsp);

response.sendRedirect("http://localhost:8080/SessionExample/MyJsp.jsp");

0 Comments:

Post a Comment

<< Home