Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Getting RequestDispatcher from request/context

 
Mohit Jain
Ranch Hand
Posts: 74
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Ranchers

I have two doubts -

1.What's the difference between getting a RequestDispatcher from - 'request' object and from 'ServletContext' object.

2. They say - "You must use the forward slash "/" with the getRequestDispatcher() method of ServletContext". Why is it so??

Please help me understand this.
 
Marc Peabody
pie sneak
Sheriff
Posts: 4727
Mac Ruby VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Every client request is submitted with a URL. So every request object on the server is tied to some URL.

ServletContext, on the other hand, is basically the web application itself. It was not created because of any URL. It is created when the container is started.

So if a request object was the result of a URL of "http://javaranch.com/someWebApp/folder/directories/finance" and you ask the request for a RequestDispatcher with "result.jsp", it will say "Hmmm, no leading slash means it wants me to make a new URL relative to my own. That means it wants http://javaranch.com/someWebApp/folder/directories/result.jsp! Piece of cake!"

But if you try the same thing to the ServletContext, it says "Are you kidding me!?! I've got like 100 places to look for this dumb file - and if I find two or more by the name result.jsp I have no clue which one you really want! Just give me the full directory structure *starting with a leading slash* from my root and I'll help you out. Throw me a freakin' bone here!"
 
Mohit Jain
Ranch Hand
Posts: 74
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a ton Marc, for a brilliant explanation!!

However, what difference does it make if we get a RequestDispatcher from a 'request' object OR a 'ServletContext'.
Which is the preferred way??? Is it ServletContext?? if yes then why??

Please help.
[ December 24, 2007: Message edited by: Mohit Jain ]
 
Remko Strating
Ranch Hand
Posts: 893
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There is no preferred way, but

I would choose the RequestDispatcher from the ServletContext, because when you reorganize your servlet with as a result that the relative locations will differ you don't have to change your code.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic