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中加入如下代码
webAppRootKey
b2cweb.root
org.springframework.web.util.WebAppRootListener
在类中获取根目录如下
//执行后rootPath 为/D:/Workspace/tourservice/WebContent
String rootPath = System.getProperty("b2cweb.root");
本文介绍了Java开发中获取Web应用根目录的两种常见方法:一是通过类路径资源获取,二是利用Spring WebAppRootListener。作者详细展示了代码实现,并讨论了它们在实际项目中的应用场景。

2379

被折叠的 条评论
为什么被折叠?



