• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Question for Kathy

 
Ranch Hand
Posts: 243
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 4982
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 138
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Mary.

Nick
 
The overall mission is to change the world. When you've done that, then you can read this tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic