Does context.RequestDispatcher expect an absolute path to be relative to the webapp root or the server root? What about response.sendRedirect()?

Alex Chaffee

According to the Servlet 2.2 spec, "The getRequestDispatcher method takes a String argument describing a path within the scope of the ServletContext. This path must be relative to the root of the ServletContext."

Thus, for a webapp (context) called "shopping", the URL

http://www.foo.com/shopping/service/support.html
is accessed with the call
context.getRequestDispatcher("/service/support.html")

However, the response.sendRedirect() method expects its path parameter to be relative to the server root, not the webapp root. Thus, to send a redirect to the above URL from a servlet running on www.foo.com, you must say
response.sendRedirect("/shopping/service/support.html");
or, more generally,
response.sendRedirect(request.getContextPath() + "/service/support.html");

Note that a path beginning with "/" is often called an "absolute URL," but this is misleading, since

  • A URL must begin with a protocol and hostname ("http://www.foo.com"), so it's actually a path, not a URL.
  • The path is not technically absolute, since it's sometimes relative to the server root, as described above.

0 Comments  (click to add your comment)
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact