java 获取web根目录的方法我目前用到的有两种:
1,获取类方法所在的目录截取根目录
//在类FreemarkerUtil中获取其class目录
//执行后path为/D:/Workspace/tourservice/WebContent/WEB-INF/classes/
String path = FreemarkerUtil.class.getClassLoader().getResource("").getPath();
//执行后rootPath 为/D:/Workspace/tourservice/WebContent
String rootPath = path.substring(0, path.indexOf("/WEB-INF/"));
rootPath为web项目的根目录。
2,通过spring配置获取根目录
在web.xml中加入如下代码
<context-param>
<param-name>webAppRootKey</param-name>
<param-value>b2cweb.root</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.util.WebAppRootListener</listener-class>
</listener>
在类中获取根目录如下
//执行后rootPath 为/D:/Workspace/tourservice/WebContent
String rootPath = System.getProperty("b2cweb.root");