YouTrack 2.0
The moose likes Web Component Certification (SCWCD) and the fly likes Getting RequestDispatcher from request/context The Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


JavaRanch » Java Forums » Professional Certification » Web Component Certification (SCWCD)
Reply Bookmark "Getting RequestDispatcher from request/context " Watch "Getting RequestDispatcher from request/context " New topic
Author

Getting RequestDispatcher from request/context

Mohit Jain
Ranch Hand

Joined: Jun 04, 2007
Posts: 74
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.

SCJP 5.0<br />SCWCD in progress
Marc Peabody
pie sneak
Sheriff

Joined: Feb 05, 2003
Posts: 4687
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!"

A good workman is known by his tools.
Mohit Jain
Ranch Hand

Joined: Jun 04, 2007
Posts: 74
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

Joined: Dec 28, 2006
Posts: 891
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.

Remko (My website)
SCJP 1.5, SCWCD 1.4, SCDJWS 1.4, SCBCD 1.5, ITIL(Manager), Prince2(Practitioner), Reading/ gaining experience for SCEA,
 
jQuery in Action, 2nd edition
 
subject: Getting RequestDispatcher from request/context
 
aspose file troubles