在 Servlet 容器中獲取 Web 應用的絕對物理路徑,主要有以下幾種方式:
request.getRealPath() —— 已過期,不推薦使用this.getServletContext().getRealPath() —— 標準 Servlet 寫法this.getServlet().getServletContext().getRealPath() —— Struts 1 時代常用request.getSession().getServletContext().getRealPath() —— 通用但有隱患當一個 EAR 包含多個 WAR 模塊並配置了會話共享時,request.getSession() 可能返回其他模塊的 Session,進而導致 getServletContext() 指向錯誤的 Web 應用上下文,最終獲取到錯誤的絕對路徑。
始終使用 this.getServlet().getServletContext().getRealPath() 或 getServletContext().getRealPath()。這兩種方式直接綁定當前 Servlet 所屬的 Web 應用上下文,不受 Session 共享影響。
// ❌ 風險寫法:EAR 多模塊共享 Session 時可能取錯路徑
String badPath = request.getSession().getServletContext().getRealPath("/upload");
// ✅ 安全寫法:綁定當前 Servlet 的上下文
String goodPath = getServletContext().getRealPath("/upload");
// 或在 GenericServlet/HttpServlet 子類中
String goodPath2 = this.getServletContext().getRealPath("/upload");
ServletContext 或使用 ResourceLoader 獲取資源。理解 ServletContext 與 Session 的生命週期差異,是避免路徑獲取錯誤的關鍵。堅持使用當前 Servlet 綁定的 ServletContext,能從根源上消除多模塊部署帶來的路徑混亂風險。