Win a copy of Java EE 8 High Performance this week in the Java/Jakarta EE forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

difference between ways of getting RequestDispatcher  RSS feed

Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello ,
Tried googling and looking at various posts in Javaranch for the differnece between getting a RequestDispatcher from servletContext and from request .

What I understand is ::
Request :: The path can be "relative" or the path can be "literal"

ServletContext :: The Path must be literal

If in Tomcat I have the following structure ::

( JSP location )
<<TOMCAT_HOME>> / webapps / myApp / view/display.jsp

( Actual servlet location )
<<TOMCAT_HOME>> / webapps / classes / com / ex / serv1.class

In my servlet I tried both of these and it worked .

So I am still not quite sure where there would be a need to use a specific Request dispatcher ?

[ August 01, 2008: Message edited by: anagha desai ]
Author and all-around good cowpoke
Posts: 13078
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here is the source of getRequestDispatcher in the Tomcat 5.5 implementation of HttpServletRequest

Figure it out.

Posts: 4181
IntelliJ IDE Java Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The request.getRequestDispatcher will get a dispatcher that locates content in the SAME CONTEXT as the request getting the dispather. So if you were at the URL:
and you wanted to get a URL at
Then you would use a request.getRequestDispatcher with a relative URL (not beginning with /).

If, on the other hand you wanted to get a page in the SAME CONTEXT but a different sub context, then you would still use the request.getRequestDispatcher with an absolute URL (beginning with /) which will be discovered relative to the same Context the request was made to.

In this same scenario you could use getServletContext().getRequestDispatcher and access the second URL in the same way as with request.getRequestDispatcher, so there would be no difference between a RequestDispatcher retrieved from the current servlet context and one retrieved from the request with a URL that started with "/".

But the ServletContext#getRequestDispatcher allows you to get pages from a DIFFERENT CONTEXT by using getServletContext().getContext("differntcontext").getRequestDispatcher.

You can't get a RequestDispatcher from a different Context using the request.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!