Friday, December 28, 2012

ServletContext#getRealPath in Tomcat/Jetty

There is a difference of the context path returned by javax.servlet.ServletContext#getRealPath between in Tomcat and in Jetty.

System.out.println(getServletContext().getRealPath("/"));
// Tomcat : /path/to/webapp/dir/
// Jetty  : /path/to/webapp/dir

In order to get a full URL, you shouldn't directly concatenate a relative path string with the context path.

System.out.println(getServletContext().getRealPath("/") + "foo.properties");
// Tomcat : /path/to/webapp/dir/foo.properties
// Jetty  : /path/to/webapp/dirfoo.properties

Such code is error-prone no matter whether or not the production environment differs from the development one. Consider using an URI builder, like:

  • java.net.URI
  • java.ws.core.UriBulder (JAX-RS)
  • org.springframework.web.util.UriComponentsBuilder (Spring Framework)