This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
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?
"The good news about computers is that they do what you tell them to do. The bad news is that they do what you tell them to do." -- Ted Nelson
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.
In preparing for battle I have always found that plans are useless, but planning is indispensable. -- Dwight D. Eisenhower