I'm using version 2.4 of Servlet
and I need to get the ContextPath
through the init()
method which is called on server start, so I don't have any Request object that could call getContextPath()
and because the Servlet version I do not have getContextPath()
method in the ServletContext
either.
Is there a way to get this ContextPath()
somehow ?
Try this code:
It should work
You are right in Servlet 2.4 the object ServeltContext does not have the method getContextPath.
I can suggest two options:
Set the context path as parameter of the servlet:
<servlet
></servlet
>Try to determine the context path from the method getRealPath()
http://tomcat.apache.org/tomcat-5.5-doc/servletapi/javax/servlet/ServletContext.html#getRealPath(java.lang.String)
According to the documentation:
It seems to be only possible form servlet 2.5 as explained in this post: ServletContext getContextPath()
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()
toServletContext
, 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 formjndi://hostname/context/...
. Thus you may be able to useto get the context path on Tomcat (or possibly
getResource("/WEB-INF/web.xml")
and trim off the tail, asgetResource()
is specified to returnnull
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.