• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Question for Kathy

 
Vijay Vaddem
Ranch Hand
Posts: 243
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

There are two ways of getting a reference to RequestDispatcher
interface.

My question is:

When to use either ServletContext.getRequestDispatcher(String resource)

and when should we go for

ServletRequest.getRequestDispatcher(String resource)

It would be nice if you can give a couple of simple examples...

TIA

Vijay
 
Nicholas Cheung
Ranch Hand
Posts: 4982
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The difference is:

You can pass a relative path to the ServletRequest.getRequestDispatcher(String), but NOT to ServletContext.getRequestDispatcher(String).

For example,

request.getRequestDispatcher("../relative.html") is correct, but for servlet.getRequestDispatch(), it MUST start with "/", for example, servlet.getRequestDispatch("/noRelative.html").

Nick
 
Mary Wallace
Ranch Hand
Posts: 138
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Just adding little bit more to Nicholas post


Since ServletRequest.getRequestDispatcher(java.lang.String) can take a relative path, it has limitations. The relative path cannot extend outside the current servlet context. Where as with ServletContext.getRequestDispatcher(java.lang.String) you can access resources from foreign contexts too.
this is very similar to a difference between session attribute and context attribute. session attriute set in program running in one jvm can be accessed by program running in other jvm. same is not true for context attribute.
 
Nicholas Cheung
Ranch Hand
Posts: 4982
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Mary.

Nick
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic