web项目中java类怎么访问WebRoot目录下的xml文件,路径怎么写?

把项目部署到Tomcat中,然后访问项目的一个页面,在页面中调用src下的一个java类,在这个java类中要访问(读取)这个web项目WebRoot下的一个xml文件。路径怎么写?谢谢!

第1个回答  2010-06-04
拷贝下面这个类,然后测试一下里面的path

/**
* 在如下环境下进行了测试
* <pre>
* Test Environment
* Windows Linux Unix
* Tomcat6.0.10
* Resin3.1.1
* Jboss4.0.0/5.0.0
* WebLogic9.1
* WebSphere6.1
* WasCE1.1
* Apusic4.0.3
* JFox3
* Jetty6.1.3
* </pre>
*
*/
public abstract class Path{

public static final String CLASS_PATH;
public static final String WEB_INF_PATH;
public static final String APP_PATH;
public static final String ROOT_PATH;

public static final String UserRegister;//玩家注册
public static final String sqlFilePath;//sql临时保存文件

static{
String currentPath=getPath(Path.class);
if(currentPath.indexOf(".jar!/")>-1||currentPath.indexOf("classes")>-1){
String classPath=currentPath.replaceAll("/./","/"); //weblogic

classPath=classPath.replaceAll("/lib/([^\'']+)!/","/classes/"); //jar
classPath=classPath.split("/classes/")[0]+"/classes/";
//if os is not windows system
if(classPath.indexOf(':')<0){
classPath='/'+classPath;
}
CLASS_PATH=classPath;
}else{
CLASS_PATH=Path.class.getClassLoader().getResource(".").getPath().substring(1);
}

WEB_INF_PATH=CLASS_PATH.substring(0,CLASS_PATH.substring(0,CLASS_PATH.lastIndexOf('/')).lastIndexOf('/')+1);

APP_PATH=WEB_INF_PATH.substring(0,WEB_INF_PATH.substring(0,WEB_INF_PATH.lastIndexOf('/')).lastIndexOf('/')+1);

ROOT_PATH=CLASS_PATH.substring(0,CLASS_PATH.indexOf('/')+1);

UserRegister=WEB_INF_PATH+"register.properties";
sqlFilePath =WEB_INF_PATH+"sqlFile.txt";
//UserRegister=WEB_INF_PATH.substring(0,WEB_INF_PATH.indexOf("WebRoot"))+"src/com/farmerwar/user/register.properties";
}

/**
* 获取参数cls的目录路径
* @param cls
* @return
*/
public static String getPath(Class<?> cls){
String t=getAbsoluteFile(cls);
return t.substring(0,t.lastIndexOf('/')+1).replaceAll("(file:/)|(file:)|(wsjar:)|(jar:)|(zip:)","");
// t=t.replaceAll("file:/", ""); //windows
// t=t.replaceAll("file:", ""); //linux,unix
// t=t.replaceAll("wsjar:",""); //websphere wsjar: has to at jar: before
// t=t.replaceAll("jar:",""); //tomcat,jboss,resin,wasce,apusic
// t=t.replaceAll("zip:",""); //weblogic
}

/**
* 获取参数cls的文件路径
* @param cls
* @return
*/
public static String getAbsoluteFile(Class<?> cls){
return cls.getResource(cls.getSimpleName() + ".class").toString().replaceAll("%20", " ");
}

public static void main(String args[]){

System.out.println(Path.WEB_INF_PATH);

}
}
第2个回答  2010-06-04
最坏的使用绝对路径本回答被提问者采纳
第3个回答  2010-06-04
如果你部署到tomcat里面的话,那就要看你web.xml怎么配的
相似回答