程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> JAVA綜合教程 >> web項目中各種路徑的獲取,web項目路徑獲取

web項目中各種路徑的獲取,web項目路徑獲取

編輯:JAVA綜合教程

web項目中各種路徑的獲取,web項目路徑獲取


以工程名為/DemoWeb為例: 
訪問的jsp為:http://localhost:8080/DemoWeb/test/index.jsp 

1 JSP中獲得當前應用的相對路徑和絕對路徑 
(1)得到工程名:request.getContextPath() 
結果:/DemoWeb 

(2)得到包含工程名的當前頁面全路徑:request.getRequestURI() 
結果:/DemoWeb/test/testpath.jsp 

(3)得到IE地址欄地址:request.getRequestURL() 
結果:http://localhost:8080/DemoWeb/test/testpath.jsp 


(4)得到當前頁面所在目錄下全名稱:request.getServletPath() 
結果:/test/testpath.jsp 

(5)得到頁面所在服務器的全路徑(實際的路徑):application.getRealPath("testpath.jsp") 
結果:D:\Develop Files\apache-tomcat-5.5.15\apache-tomcat-5.5.15\webapps\DemoWeb\testpath.jsp 
D:\Develop Files\apache-tomcat-5.5.15\apache-tomcat-5.5.15為tomcat的安裝路徑 

 

(6) Web應用中有各種獲取path或URI,URL的方法,假設網頁訪問地址:

http://localhost:8080/tradeload/TestServlet

Web應用context: /tradeload 

  1. request.getContextPath()= /tradeload   
  2. request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()= http://localhost:8080   
  3. request.getRequestURL() = http://localhost:8080/tradeload/TestServlet   
  4. request.getRequestURI() = /tradeload/TestServlet   
  5. request.getPathInfo() = null   
  6. request.getServletPath() = /TestServlet   
  7. getServletContext().getRealPath('/') = C:\server\glassfish\domains\domain1\applications\j2ee-modules\tradeload\

2.java 的Class中獲得相對路徑,絕對路徑的方法 

(1)類的絕對路徑: 
System.out.println(TestPath.class.getResource("/").getPath()); 
結果:/E:/workspace/workspace_tcc/DemoWeb/WebRoot/WEB-INF/classes/ 

System.out.println(TestPath.class.getResource("")); 
結果:file:/E:/workspace/workspace_tcc/DemoWeb/WebRoot/WEB-INF/classes/demo1/ 


(2)得到工程的路徑:System.getProperty("user.dir") 

結果:E:\workspace\workspace_tcc\DemoWeb 

(3)得到項目部署的絕對路徑:

//獲取運行項目名稱
WebApplicationContext wac = ContextLoader.getCurrentWebApplicationContext();
ServletContext sc =wac.getServletContext();
String projectName = sc.getContextPath();

//獲取運行項目路徑 即tomcat下的項目路徑(默認情況下)
//tomcat conf server.xml配置文件若有配置項目路徑<Context path="" docBase="D:\seed" reloadable="false" />,則是該docBase的路徑
WebApplicationContext webApplicationContext = ContextLoader.getCurrentWebApplicationContext();
ServletContext servletContext = webApplicationContext.getServletContext();
String projectPath=servletContext.getRealPath("/").replace("\\", "/");

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved