Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

A question on RequestDispatcher

 
Johnson David
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,

I think this is one of the common questions in servlets.

What is the difference between a RequestDispatcher object obtained from the Request object and the RequestDispatcher object obtained from the ServletContext ?


thanks in advance

Johnson
 
vishwanath nadimpally
Ranch Hand
Posts: 116
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by johnson david:
Hi all,

I think this is one of the common questions in servlets.

What is the difference between a RequestDispatcher object obtained from the Request object and the RequestDispatcher object obtained from the ServletContext ?


thanks in advance

Johnson


Hi john,
This is from a search result i did on google for your question:

"from javadoc

getRequestDispatcher

public RequestDispatcher getRequestDispatcher(java.lang.String path)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.
The pathname specified may be relative, although it cannot extend outside the current servlet context. If the path begins with a "/" it is interpreted as relative to the current context root. This method returns null if the servlet container cannot return a RequestDispatcher.

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

What this means is that with the ServletContext's RequestDispatcher, the path is always set to the root of the context , ie '/' as compared to the Request's RequestDispatcher where you could specify a path relative to the resource servicing that request.

A simple example

Assume the resource that's servicing the current request is servlet/FirstServlet

Assume, i need to get to a resource /servlet/someOtherServlet using a request disptacher.


RequestDispatcher rd = getServletContext().getRequestDispatcher("/servlet/someOtherServlet");
rd.include(request, response);

Alternatively

RequestDispatcher rd = request.getRequestDispatcher("someOtherServlet"); //path relative to firstServlet
rd.include(request, response);"
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic