Spring中获取web项目的根目录

spring 在 org.springframework.web.util 包中提供了几个特殊用途的 Servlet 监听器,正确地使用它们可以完成一些特定需求的功能; WebAppRootListener 可以将 Web 应用根目录添加到系统参数中,对应的属性名可以通过名为“webAppRootKey”的 Servlet 上下文参数指定

配置方法

web.xml文件中
<context-param>  
    <param-name>webAppRootKey</param-name>   
    <param-value>web.root</param-value>  
</context-param>  
<listener>   
    <listener-class>org.springframework.web.util.WebAppRootListener</listener-class>  
</listener>

使用方法:

1) 在java代码中使用String rootPath = System.getProperty("web.root")获取web项目根目录

String path = System.getProperty("web.root")+"/productImages";

2) 在配置文件resource.properties中使用

更常见的使用场景是在配置文件中通过 ${web.roott} 引用 Web 应用的根目录

#存放商品图片目录
PRODUCT_IMAGES_PATH=${web.root}/productImages

如果有不正确, 请指出, 谢谢

原文地址:https://www.cnblogs.com/guo-rong/p/9644900.html