Hi, Is there any difference between obtaining a RequestDispatcher from HttpServletRequest or ServletContext? ( request.getRequestDispatcher( ) or getServletContext().getRequestDispatcher( )? ) Regards, -Ruud.
The getRequestDispatcher() method in ServletContext accepts only absolute URLs which begin with a /. The getRequestDispatcher() method in ServletRequest accepts both absolute and relative URLs. This being said, it is easy to see that ServletContext.getRequestDispatcher() is not of much use and should soon be deprecated.
Valentin Crettaz wrote: This being said, it is easy to see that ServletContext.getRequestDispatcher() is not of much use and should soon be deprecated. In a reasonable sized web application you often need to refer to resources located a specific location in the web application. Just as you often need to refer to things relative to the current request path. Think of things like a common "login" page, or maybe an application wide help page, or some common page fragments "included" by pages from several "sub-sites". Although you could refer to these using some sort of relative path ("../../login.jsp"), that just makes moving pages around and re-using them harder. Much nicer to refer to them from the application root ("/login.jsp").
Hello But the request.getRequestDispatcher() does both the jobs correctly. So really it is not necessary to use the ServletContext version. Rajesh Kumar SCJP2, SCWCD, UML, J2EE
Joined: Aug 26, 2001
Frank, I must admit that the last sentence I wrote above does not come from me (but I kinda agree with it). It comes from Jason Hunter's JavaServlet Programming book (2nd edition page 371)... Quote from the book:
... Consequently, there's no reason to use the method in ServletContext (speaking of the getRequestDispatcher() method). It exists only for historical reasons and can be considered deprecated although officially it's not.
[ July 18, 2002: Message edited by: Valentin Crettaz ]
Joined: Jan 07, 1999
OK. I gesss I'd never realized that the other one does both tasks. Too much trust in the separation of responsibilities in the API. I really should have learned by now... Thanks guys.
Btw, though it is used very rarely, there is one reason for ServletContext.getRequestDispatcher() to exist; it allows us to forward a request to a resource in another web application (read another context) ServletContext.getContext(otherContextPath).getRequestDispatcher(resourcePath); We cannot achieve that by using ServletRequest only. -j