萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Java 相對與絕對路徑完整指南:Servlet、JSP、獨立類別、主流伺服器實戰

核心 API 對照表

場景取得 Web 應用根目錄絕對路徑取得當前類別/類別路徑取得請求相關路徑
Servlet (init)getServletContext().getRealPath("/")getClass().getClassLoader().getResource("").getPath()request.getServletPath() / request.getRequestURI()
任意類別同上或 Thread.currentThread().getContextClassLoader().getResource("").getPath()MyClass.class.getResource("") (類別目錄)
MyClass.class.getResource("/") (classpath 根)
無 request 物件
JSPapplication.getRealPath("/")pageContext.getServletContext().getRealPath("/")request.getRequestURI()、request.getServletPath()

常用路徑取得方式詳解

1. Web 應用根目錄 (WebRoot)

// Servlet
String webRoot = getServletContext().getRealPath("/");
// JSP
String webRoot = application.getRealPath("/");
// 結果範例: E:/workspace/myapp/

2. WEB-INF/classes 目錄 (Classpath 根)

// 任意類別
String classesPath = MyClass.class.getClassLoader().getResource("").getPath();
// 或
String classesPath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
// 結果範例: file:/E:/workspace/myapp/WEB-INF/classes/

3. 當前類別所在目錄

String currentClassDir = MyClass.class.getResource("").getPath();
// 結果範例: file:/E:/workspace/myapp/WEB-INF/classes/com/example/

4. 請求相關路徑

  • request.getRequestURI():含 context path 的完整 URI(如 /myapp/user/profile)。
  • request.getServletPath():對應 web.xml 映射路徑(如 /user/profile)。
  • request.getContextPath():Context Path(如 /myapp)。
  • request.getRealPath(uri):將 URI 轉為伺服器端絕對檔案路徑。

主流伺服器 user.dir 差異

伺服器System.getProperty("user.dir")備註
WebLogicWebLogic 安裝根目錄建議使用絕對路徑或相對 ./config/xxx.properties
Tomcat%CATALINA_HOME%/bin啟動腳本工作目錄
ResinResin 安裝目錄JSP 編譯後 Servlet 執行目錄

最佳實務建議

  1. 資源檔案放在 classpath:使用 getResourceAsStream("/config.properties") 讀取,不依賴檔案系統路徑。
  2. 上傳/生成檔案:配置外部化儲存目錄(如 /data/app/uploads),透過屬性檔/環境變數注入,避免寫入 Web 應用目錄(重新部署會丟失)。
  3. 跨平台路徑:使用 File.separator、Paths.get() (NIO.2) 構建路徑。
  4. 單元測試:獨立類別測試時,ClassLoader.getSystemResource("") 指向 target/test-classes。

結語

Java 路徑問題核心在於「誰在執行、當前工作目錄是哪裡、classpath 根在哪裡」。掌握上述 API 對照表並遵循「資源走 classpath、資料走外部目錄」原則,即可徹底擺脫路徑困擾。

copyright © 萬盛學電腦網 all rights reserved