java 獲取web根目錄的方法我目前用到的有兩種:
1,獲取類方法所在的目錄截取根目錄
//在類FreemarkerUtil中獲取其class目錄
//執行後path爲/D:/Workspace/tourservice/WebContent/WEB-INF/classes/
String path = FreemarkerUtil.class.getClassLoader().getResource("").getPath();
//執行後rootPath 爲/D:/Workspace/tourservice/WebContent
String rootPath = path.substring(0, path.indexOf("/WEB-INF/"));
rootPath爲web項目的根目錄。
2,通過spring配置獲取根目錄
在web.xml中加入如下代碼
<context-param>
<param-name>webAppRootKey</param-name>
<param-value>b2cweb.root</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.util.WebAppRootListener</listener-class>
</listener>
在類中獲取根目錄如下//執行後rootPath 爲/D:/Workspace/tourservice/WebContent
String rootPath = System.getProperty("b2cweb.root");