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")调用全路路径了。