public static String getPath() { //獲得當前的classpath的絕對路徑的URI表示法 String path=Thread.currentThread().getContextClassLoader().getResource("").toString(); // 將/換成\ 去掉file: //去掉classes\ 去掉第一個\,如 \D:\JavaWeb... path=path.replace('/', '\\').replace("file:", "").replace("classes\\", "").substring(1); return path; } //得到項目絕對路徑 public static String getProjectRootPath(){ String rootPath=Thread.currentThread().getContextClassLoader().getResource("").getPath(); rootPath = rootPath.substring(1,rootPath.indexOf("WEB-INF")); return rootPath; }
classpath:只能服務器才能使用。客戶端不能訪問這個路徑下的內容。web
例如:項目名是testapache
D:/apacheTomcat/apache-tomcat-7.0.59/webapps/test/WEB-INF/classes/
D:/apacheTomcat/apache-tomcat-7.0.59/webapps/test/
@Autowired private HttpServletRequest request; @Test public void testUrl(){ String schema = request.getScheme(); String serverName = request.getServerName(); // 端口號返回的是int類型 int serverPort = request.getServerPort(); String contextPath = request.getContextPath(); String servletPath = request.getServletPath(); System.out.println("協議:"+schema); System.out.println("服務器名稱:"+ serverName); System.out.println("服務器端口號:"+ serverPort); System.out.println("項目名稱:"+ contextPath); System.out.println("servlet路徑:"+ servletPath); }