方法1:java
ServletActionContext.getServletContext().getRealPath(File.separator);//项目根路径如D:\xxx\项目名
这个方法若是在action的通常方法中执行没问题可获得,可是放到static初始化中时就会报错:web
private static String basePath; static { basePath = ServletActionContext.getServletContext().getRealPath(File.separator); }
具体为何没有研究出来app
方法2:webapp
basePath = ProductStage.class.getClassLoader().getResource("")
获得的字符串是形如:code
D:/Java/Tomcat%206.0/webapps/项目名/WEB-INF/classes字符串
并且若是路径中包含空格的话会显示为“%20”,要替换截取获得想要的路径如:get
basePath = ProductStage.class.getClassLoader().getResource("") .getFile().replaceAll("/WEB-INF/classes/", "").replaceAll("%20", " ").substring(1);