java web 物理路径_WEB 项目中JAVA取得WEBROOT物理路径

http://wwwzhouhui.iteye.com/blog/504330

————————————————————————————————————————————————————————————————————

.最近项目中应用到JAVA 后台代码取得WEBROOT物理路径的问题,网上找了点资料学习了一下

我们知道JSP Servlet 取得WEB根路径可以用request.getContextPath(), 相对路径request.getSession().getServletContext().getRealPath("/") 物理路径 绝对路径

这2个相对有方法可以使用我们很容易取得根路径

2.JAVA 中取得系统路径可以使用System.getProperty("user.dir"); 但是我要取得WEB的物理路径如何取得呢,JAVA中不能继承或者取得到request  ServletContext 等WEB的上下文就不能直接用API 函数取得了

3.spring框架的思路, 在WEB -INF/web .xml 中 , 创建一个webAppRootKey的param, 指定一个值(默认为webapp.root)作为键值, 然后通过Listener , 或者Filter , 或者Servlet 执行String webAppRootKey = getServletContext().getRealPath("/"); 并将webAppRootKey对应的webapp.root 分别作为Key , Value写到System Properties系统属性中。之后在程序中通过System.getProperty("webapp.root")来获得WebRoot的物理路径

4.实践

web.xml

webAppRootKey

csc2.root

test.ApplicationListener

ApplicationListener.java

packagetest;importjavax.servlet.ServletContextEvent;importorg.springframework.web.context.ContextLoaderListener;/***********************************************************************

*

* ApplicationListener.java

* @copyright Copyright: 2009-2012

* @creator 周辉

* @create-time Oct 26, 2009 2:33:35 PM

* @revision $Id: *

***********************************************************************/

public class ApplicationListener extendsContextLoaderListener {public voidcontextDestroyed(ServletContextEvent sce) {//TODO Auto-generated method stub

}public voidcontextInitialized(ServletContextEvent sce) {//TODO Auto-generated method stub

String webAppRootKey = sce.getServletContext().getRealPath("/");

System.setProperty("csc2.root", webAppRootKey);

String path=System.getProperty("csc2.root");

System.out.println("sssss:::"+path);

}

}

test.java

packagetest;/***********************************************************************

*

* test.java

* @copyright Copyright: 2009-2012

* @creator 周辉

* @create-time Oct 26, 2009 2:34:21 PM

* @revision $Id: *

***********************************************************************/

public classtest {public voidremve(){

String path=System.getProperty("csc2.root");

System.out.println("result::::::::"+path);

}

}

index.jsp

String basePath= request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%>

t.remve();%>

部署程序发布 启动TOMCAT 运行index.jsp  就可以调用JAVA中全局设置的物理路径了(说明这里的JSP 只是调用了TEST.JAVA 的remove方法,不做其他使用

原理解释,TOMCAT 启动和 读取WEB.XML 监听方式加载SPRING ApplicationListener 继承SPRING ContextLoaderListener 加载SPRING 顺便吧全局路径赋值给csc2.root 描述,这样之后JAVA 代码中就可以使用System.getProperty("csc2.root")调用全路路径了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值