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

独自空忆成欢 提交于 2019-12-05 05:28:16

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.

krampstudio

It seems to be only possible form servlet 2.5 as explained in this post: ServletContext getContextPath()

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

I can suggest two options:

  1. Set the context path as parameter of the servlet:

    <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>

  2. 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:

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

Try this code:

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

It should work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!