首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 綜合教學

Web 項目路徑獲取大全:request、application、Class 多維度實戰速查

     編輯:Java 綜合教學

基於 HttpServletRequest 的路徑 API

假設訪問地址:https://localhost:8080/DemoWeb/test/index.jsp

方法返回值說明
getContextPath()/DemoWeb項目上下文路徑(部署名)
getRequestURI()/DemoWeb/test/index.jsp含項目名的資源路徑
getRequestURL()https://localhost:8080/DemoWeb/test/index.jsp完整請求 URL
getServletPath()/test/index.jspServlet 映射路徑
application.getRealPath("/")D:\Tomcat\webapps\DemoWeb\項目在服務器的物理絕對路徑

另一組經典案例

訪問:https://localhost:8080/tradeload/TestServlet

  1. request.getContextPath() = /tradeload
  2. request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() = https://localhost:8080
  3. request.getRequestURL() = https://localhost:8080/tradeload/TestServlet
  4. request.getRequestURI() = /tradeload/TestServlet
  5. request.getPathInfo() = null(無額外路徑信息)
  6. request.getServletPath() = /TestServlet
  7. getServletContext().getRealPath("/") = 物理部署根目錄

Java 類級路徑獲取

// 類加載器視角:獲取 classes 目錄
TestPath.class.getResource("/").getPath();
// 結果: /E:/workspace/DemoWeb/WebRoot/WEB-INF/classes/

// 當前包目錄
TestPath.class.getResource("");
// 結果: file:/E:/workspace/DemoWeb/WebRoot/WEB-INF/classes/demo1/

系統屬性與 Spring 上下文路徑

// 項目工作目錄
System.getProperty("user.dir");
// 結果: E:\workspace\DemoWeb

// Spring 環境下獲取項目真實路徑(推薦)
WebApplicationContext wac = ContextLoader.getCurrentWebApplicationContext();
ServletContext sc = wac.getServletContext();
String projectPath = sc.getRealPath("/").replace("\\", "/");

注意: 若 server.xml 配置了 <Context docBase="D:\seed" />,則以該路徑為準。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved