我正在使用版本2.4的Servlet
,我需要通過init()
方法得到ContextPath
方法,因此我沒有任何請求對象可能會調用getContextPath()
,並且因爲Servlet版本I在ServletContext
中也沒有getContextPath()
方法。如何在Servlet版本2.4的init()方法中獲取ContextPath
有沒有辦法讓這ContextPath()
莫名其妙?
我正在使用版本2.4的Servlet
,我需要通過init()
方法得到ContextPath
方法,因此我沒有任何請求對象可能會調用getContextPath()
,並且因爲Servlet版本I在ServletContext
中也沒有getContextPath()
方法。如何在Servlet版本2.4的init()方法中獲取ContextPath
有沒有辦法讓這ContextPath()
莫名其妙?
試試這個代碼:
class demo extends HttpServlet {
public void init(ServletConfig config) {
String path = config.getServletContext().getRealPath("/");
}
}
它應該工作
這將給webapp目錄(例如'/ var/tomcat/webapps/foo')提供真正的文件系統路徑,而不是部署應用程序的上下文路徑('/ foo') 。正如krampstudio所說的,Servlet 2.5將'getContextPath()'添加到'ServletContext'中,爲應用程序返回「主」上下文路徑,但在2.4或更早版本中,您只能獲取特定請求的路徑。 –
這似乎是唯一可能的形式的servlet 2.5在這篇文章解釋說:ServletContext getContextPath()
你是對的在Servlet 2.4中的對象ServeltContext沒有方法getContextPath。
我可以建議兩個選項:
設置上下文路徑作爲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
>
嘗試確定來自t的上下文路徑他方法getRealPath()
根據文檔:
返回包含對於給定的虛擬路徑的實際路徑的字符串。 例如,路徑「/index.html」返回 上的絕對文件路徑,服務器的文件系統將由 「http://host/contextPath/index.html」請求提供服務,其中contextPath是上下文路徑這個ServletContext。
一個Web應用程序可以在多個不同的上下文路徑被公開,所以在上下文路徑(單數)是僅在特定請求的上下文中有意義。 Servlet 2.5添加了getContextPath()
到ServletContext
,指定爲此Web應用程序返回「主」上下文路徑,但在以前的spec版本中沒有獨立於容器的方式來訪問此信息。
可能有些技巧適用於某些容器,例如在Tomcat上,ServletContext.getResource()
方法返回帶有定製方案的URL,格式爲jndi://hostname/context/...
。因此,您可以使用
ctx.getResource("/").getPath()
獲得在Tomcat上下文路徑(或可能getResource("/WEB-INF/web.xml")
和剪掉尾巴,爲getResource()
被指定爲返回null
如果你問它是不存在的文件) 。你將不得不嘗試使用不同的容器來尋找類似的技巧。
[ServletContext.getServletContextName()](http://docs.oracle.com/javaee/1.4/api/javax/servlet/ServletContext.html#getServletContextName()) - 。ServletConfig.getServletContext()getServletContextName() –
在我的情況下這是空的:/ – Lama