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
posted
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
posted
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??
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.