文件路徑獲取錯誤

###1.背景描述 某文件的絕對路徑結構: ....../Mobile/src/main//webapp/style/css/test.csscss

Mobile
|src
   |--main
        |--webapp
              |--style
                  |--css
                       |--test.css   
              |WEB-INF

開發環境獲取到的文件的路徑爲java

....../Mobile/src/main//webapp/style/css/

真實環境時,將工程打成了war包,而打war包通常是從webapp層開始打包,不會將源碼打進war包中。 war包名:Mobile.warweb

文件的路徑爲app

......./Mobile/style/css

###2.錯誤獲取方式:webapp

public class StyleServlet extentHttpServlet{
    //獲取當前calss文件所在的路徑  ....../Mobile/src/main/action/startup/StyleServlet.java
    String styleServletAbsPath = StyleServlet.class.getResource("").getPath();

    //工程所在路徑  ....../Mobile/
    String projectPath = currentAbsPath.substring(1, currentAbsPath.indexOf("src")) ;

    //工程路徑 + 文件相對路徑(src/main/webapp/style/css/test.css)
    String stylesheetPath = projectPath + "src/main/webapp/style/css/test.css";
}

###3.錯誤分析 此方法只適合本地開發,即不打war包的狀況。由於打war包以後就沒有"/src/main/"這樣的路徑 若是再拿這種方式去拼接,真實環境時由於找不到"/src/main/"路徑而報錯code

###4.正確獲取方式開發

//獲取webapp或war包所在路徑
String webappAbsPath = getServletContext().getRealPath("/");

filePath = webappAbsPath + "style/css/test.css"
相關文章
相關標籤/搜索