web项目获得本地物理路径
需求:获得项目在本地的物理路径。
前期遇到的问题:使用System.getProperty("user.dir")只能获得系统路径,通常为以服务器地址开头。但这并不是自己项目的实际物理位置。
解决办法:web.xml配置+自定义监听接口+System.setProperty()
步骤1:web.xml配置属性
1 <context-param> 2 <param-name>webAppRootKey</param-name> 3 <param-value>inf-root</param-value> 4 </context-param>
步骤:2:自定义接口,并实现 ContextLoaderListener。ContextLoaderListener会在spring启动时被调用
示例:
1 import org.springframework.web.context.ContextLoaderListener; 2 3 import javax.servlet.ServletContextEvent; 4 5 public class myListener extends ContextLoaderListener { 6 @Override 7 public void contextInitialized(ServletContextEvent event) { 8 String webAppRootKey = event.getServletContext().getRealPath("/"); 9 int index = webAppRootKey.indexOf("target"); 10 if(index!=-1){ 11 webAppRootKey = webAppRootKey.substring(0,index); 12 } 13 System.setProperty("inf-root",webAppRootKey); 14 System.out.println(System.getProperty("inf-root")); 15 } 16 }
1 <!--加载物理路径监听器--> 2 <listener> 3 <listener-class>com.stuSystem.manager.listener.myListener</listener-class>//自定义接口在项目中的全路径 4 </listener>
解释:
(1)String webAppRootKey = event.getServletContext().getRealPath("/");最终获得路径为../target/当前web目录,意思是将位置定位在了target目录下。
(2)此处我将路径截取到target之外。
int index = webAppRootKey.indexOf("target");
if(index!=-1){
webAppRootKey = webAppRootKey.substring(0,index);
}
(3)System.setProperty("inf-root",webAppRootKey); 设置系统属性,方便别处调用。
参考博客:https://blog.csdn.net/wwwzhouhui/article/details/83482671?utm_medium=distribute.pc_relevant.none-task-blog-baidujs-1

浙公网安备 33010602011771号