One web application can be published at several different context paths, so the context path (singular) is only meaningful in the context of a particular request. Servlet 2.5 added getContextPath()
to ServletContext
, specified to return the "primary" context path for this web application, but there's no container-independent way to access this information in earlier spec versions.
There may be tricks that work for certain containers, for example on Tomcat the ServletContext.getResource()
method returns URLs with a custom scheme, of the form jndi://hostname/context/...
. Thus you may be able to use
ctx.getResource("/").getPath()
to get the context path on Tomcat (or possibly getResource("/WEB-INF/web.xml")
and trim off the tail, as getResource()
is specified to return null
if you ask it for a file that does not exist). You will have to experiment with different containers to find similar tricks that work on those.