//類載入根路徑String classPath = this.getClass().getResource("/").getPath();//類載入根路徑URL xmlPath = this.getClass().getClassLoader().getResource("");//類所在工程根路徑String proClassPath = this.getClass().getResource("").getPath();//專案服務器指令檔路徑File directory = new File("");// 參數為空白String proRootPath = directory.getCanonicalPath();//專案服務器指令檔路徑String proPath = System.getProperty("user.dir");// 擷取所有的類路徑 包括jar包的路徑String allClassPath = System.getProperty("java.class.path");//項目部署的路徑String path = request.getSession().getServletContext().getRealPath("/");System.out.println("類載入根路徑:" + classPath);System.out.println("類載入根路徑:" + xmlPath);System.out.println("類所在工程路徑:" + proClassPath);System.out.println("專案服務器指令檔路徑:" + proRootPath);System.out.println("專案服務器指令檔路徑:" + proPath);System.out.println("項目部署的路徑:" + allClassPath );System.out.println("擷取所有的類路徑:" + path );
結果如下:
類載入根路徑:/D:/workspace/Training2016/04-PG/0401-Source/base2016/base_web/target/base_web-1.0-SNAPSHOT/WEB-INF/classes/類載入根路徑:file:/D:/workspace/Training2016/04-PG/0401-Source/base2016/base_web/target/base_web-1.0-SNAPSHOT/WEB-INF/classes/類所在工程路徑:/D:/workspace/Training2016/04-PG/0401-Source/base2016/base_web/target/base_web-1.0-SNAPSHOT/WEB-INF/classes/com/study/mvc/專案服務器指令檔路徑:D:\apache-tomcat-8.0.361\bin專案服務器指令檔路徑:D:\apache-tomcat-8.0.361\bin項目部署的路徑:D:\workspace\Training2016\04-PG\0401-Source\base2016\base_web\target\base_web-1.0-SNAPSHOT\擷取所有的類路徑:D:\apache-tomcat-8.0.361\bin\bootstrap.jar;D:\apache-tomcat-8.0.361\bin\tomcat-juli.jar
項目路徑如圖所示,target為部署的位置
注意此處可能request擷取不到,擷取request的方法有很多:
1.通過註解擷取(推薦):public class Hello {@Autowired HttpServletRequest request; //這裡可以擷取到request}2.在web.xml中配置一個監聽:<listener> <listener-class> org.springframework.web.context.request.RequestContextListener </listener-class> </listener> java代碼:HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest(); 3.直接在參數中傳遞:public String hello(HttpServletRequest request)4.如果有Struts:HttpServletRequest request = ServletActionContext.getRequest();
有時request.getSession().getServletContext().getRealPath(“/”);擷取到的路徑不是tomcat的路徑
D:\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\....
這個的原因其實 D:\workspace.metadata.plugins\org.eclipse.wst.server.core\tmp0\ 這個目錄就是eclipse的對 D:\Tomcat 7.0 目錄的一個複製,從而使 D:\workspace.metadata.plugins\org.eclipse.wst.server.core\tmp0\ 也能夠具備原始伺服器的功能。