假設訪問地址: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.jsp | Servlet 映射路徑 |
application.getRealPath("/") | D:\Tomcat\webapps\DemoWeb\ | 項目在服務器的物理絕對路徑 |
訪問:https://localhost:8080/tradeload/TestServlet
request.getContextPath() = /tradeloadrequest.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() = https://localhost:8080request.getRequestURL() = https://localhost:8080/tradeload/TestServletrequest.getRequestURI() = /tradeload/TestServletrequest.getPathInfo() = null(無額外路徑信息)request.getServletPath() = /TestServletgetServletContext().getRealPath("/") = 物理部署根目錄// 類加載器視角:獲取 classes 目錄
TestPath.class.getResource("/").getPath();
// 結果: /E:/workspace/DemoWeb/WebRoot/WEB-INF/classes/
// 當前包目錄
TestPath.class.getResource("");
// 結果: file:/E:/workspace/DemoWeb/WebRoot/WEB-INF/classes/demo1/
// 項目工作目錄
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" />,則以該路徑為準。