java 獲取web根目錄

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");



發佈了48 篇原創文章 · 獲贊 61 · 訪問量 78萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章