aspose file tools*
The moose likes Servlets and the fly likes RequestDispatcher - best to get it from request or from context? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Servlets
Bookmark "RequestDispatcher - best to get it from request or from context?" Watch "RequestDispatcher - best to get it from request or from context?" New topic
Author

RequestDispatcher - best to get it from request or from context?

J. Kevin Robbins
Ranch Hand

Joined: Dec 16, 2010
Posts: 632
    
    7

I understand that ServletContext.getRequestDispatcher() takes a path relative to the application root, and ServletRequest.getRequestDispatcher() takes a path relative to the current requesting object. Other than that, they work exactly the same. Why do we need both?

Is this just something that changed as Java has matured and both methods were left in for backward compatibility or are there circumstances where one choice is better than the other?

Most of the code I see uses the request method, so I'm guessing this is probably the older/original way of doing things and the context method was added later for some reason?


"There is no reason for any individual to have a computer in his home" ~ Ken Olson, Co-founder of DEC, 1977
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 60053
    
  65

It's just a mater of preference. I always use the method on the request.


[Asking smart questions] [Bear's FrontMan] [About Bear] [Books by Bear]
Pete Nelson
Ranch Hand

Joined: Aug 30, 2010
Posts: 147

Jk Robbins wrote:Most of the code I see uses the request method, so I'm guessing this is probably the older/original way of doing things and the context method was added later for some reason?


I suspect the biggest reason you see the ServletRequest version used is that you already have a reference to the ServletRequest object in your do* method, so it's just easier to do request.getRequestDispatcher(...) vs getServletContext().getRequestDispatcher(...).

I've personally never called the ServletContext method, nor have I ever used a relative path.


OCPJP
In preparing for battle I have always found that plans are useless, but planning is indispensable. -- Dwight D. Eisenhower
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 60053
    
  65

The only time the context version is required is for making cross-context dispatching, which is not supported by many containers.
J. Kevin Robbins
Ranch Hand

Joined: Dec 16, 2010
Posts: 632
    
    7

Thanks to both of you. That shines some light on things and satisfies my curiosity.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: RequestDispatcher - best to get it from request or from context?
 
Similar Threads
forward() and include()
getRequestDispatcher???
context dispatcher vs requestdispatcher
Correct answer
getRequestDispatcher error in servlets