How to get ContextPath in init () method of Servlet 2.4

I am using version 2.4 from Servlet , and I need to get ContextPath through the init() method, which is called when the server starts, so I don’t have a Request object that could call getContextPath() and since the version of the servlet I don’t have getContextPath() method in ServletContext .

Is there a way to get this ContextPath() somehow?

+7
java servlets contextpath
Dec 14 '12 at 13:45
source share
4 answers

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.

+2
Dec 14
source share

It seems that only the form of servlet 2.5 is possible, as explained in this post: ServletContext getContextPath ()

+1
Dec 14
source share

You are right in Servlet 2.4, the ServeltContext object does not have a getContextPath method.

I can offer two options:

  • Set the context path as the servlet parameter:

    <servlet >

     <servlet-name>initServlet</servlet-name> <servlet-class>net.cirrus-it.InitServlet`</servlet-class> <init-param> <param-name>contextPath</param-name> <param-value>/myApp</param-value> </init-param> 

    </servlet >

  • Try to determine the context path from the getRealPath () method

http://tomcat.apache.org/tomcat-5.5-doc/servletapi/javax/servlet/ServletContext.html#getRealPath(java.lang.String )

According to the documentation:

Returns a string containing the real path for the given virtual path. For example, the path "/index.html" returns the absolute path to the file on the server file system will be served by a request for "http: //host/contextPath/index.html", where contextPath is the context path of this ServletContext.

+1
Dec 14
source share

Try this code:

 class demo extends HttpServlet { public void init(ServletConfig config) { String path = config.getServletContext().getRealPath("/"); } } 

He should work

-one
Dec 14 '12 at 13:50
source share



All Articles