One web application can be published in several different contextual paths, so the contextual path (the only one) makes sense only in the context of a specific request. Servlet 2.5 is added by getContextPath() to ServletContext specified to return the "main" context path for this web application, but there is no container-independent way of accessing this information in earlier versions of the specifications.
There may be tricks that work for specific containers, for example, in Tomcat, the ServletContext.getResource() method returns URLs with a custom scheme of the form jndi://hostname/context/... So you can use
ctx.getResource("/").getPath()
to get the context path to Tomcat (or maybe getResource("/WEB-INF/web.xml") and trim the tail since getResource() is specified to return null if you request a file that does not exist). You will have to experiment with different containers to find similar tricks that work on them.
Ian Roberts Dec 14 2018-12-12T00: 00Z
source share