现在好多配置都放在了属性文件里,由java程序调用,一般讲java的配置文件放在web-info下程序里面获取路径 通过如下方式:
1.可以在servlet的init方法里
String path = getServletContext().getRealPath("/");
这将获取web项目的全路径
例如 :E:/eclipseM9/workspace/tree/
tree是我web项目的根目录
2.你也可以随时在任意的class里调用
this.getClass().getClassLoader().getResource("/").getPath();
这将获取 到classes目录的全路径
获取上级目录的路径:
this.getClass().getClassLoader().getResource("../").getPath():
这个获取的是WEB-INO的目录全路径
这个方法也可以不在web环境里确定路径,比较好用
3.request.getContextPath();
获得web根的上下文环境
加载属性文件用到的是Apache的开源组件需要如下3个jar包:commons-configuration.jar commons-lang-2.5.jar commons-collections-3.2.jar
程序如下:
String str = this.getClass().getClassLoader().getResource("../")
.getPath();
Configuration config = new PropertiesConfiguration(str
+ "/config.properties");
u2_contype = config.getString("u2.contype");
u2_url = config.getString("u2.url");
u2_username = config.getString("u2.username");
u2_password = config.getString("u2.password");
ms_contype = config.getProperty("ms.contype").toString();
ms_username = config.getString("ms.username");
ms_password = config.getString("ms.password");
ms_url = config.getString("ms.url");
debug = config.getInt("debug");