TO: ..........qsc800528 (星空)..................
swoky 2007-08-31 09:41:34 刚才打开你上次发的那个贴子,http://community.csdn.net/Expert/topic/5736/5736360.xml?temp=.7402002
你说
....需要传request进到这个类里来,又不是Action很不情愿传过来的......
本来想在那里给予你回复的,可是你却结了,只好这样了
刚找了下我以前写的,整理了一下,对jar和class文件都有效,希望对你有帮助
------------------------------
/**
* @author swoky
* @time 2007-8-31 21:12:39
*/
public class WebRoot {
/**
*这个随你写在哪里.当然不一定就是"WEB-INF"来做判断的,以后调用这个涵数就可以了
*/
public String getWebRoot(){
String path = getClassPath(WebRoot.class);
return path.substring(0,path.indexOf("WEB-INF")-1);
}
/**
* 获取class文件的绝对路径
*/
private String getClassPath(Class cls) {
String path = null;
java.net.URL url = getClassLocationURL(cls);
if (url != null) {
path = url.getPath();
if ("jar".equalsIgnoreCase(url.getProtocol())) {
try {
path = new java.net.URL(path).getPath();
} catch (Exception e) {
System.out.print("获取class文件的绝对路径出错:" + e.getMessage());
}
int location = path.indexOf("!/");
if (location != -1) {
path = path.substring(0, location);
}
}
try {
java.io.File file = new java.io.File(path);
path = file.getCanonicalPath();
} catch (Exception ex) {
System.out.print("获取class文件的绝对路径出错:" + ex.getMessage());
}
}
return pathChange(path);
}
/**
* 获取class文件位置的URL
*/
private java.net.URL getClassLocationURL(final Class cls) {
java.net.URL result = null;
String clsAsResource = cls.getName().replace('.', '/').concat(".class");
java.security.ProtectionDomain pd = cls.getProtectionDomain();
if (pd != null) {
java.security.CodeSource cs = pd.getCodeSource();
if (cs != null)
result = cs.getLocation();
if (result != null) {
if ("file".equals(result.getProtocol())) {
try {
if (result.toExternalForm().endsWith(".jar")
|| result.toExternalForm().endsWith(".zip"))
result = new java.net.URL("jar:".concat(
result.toExternalForm()).concat("!/")
.concat(clsAsResource));
else if (new java.io.File(result.getFile())
.isDirectory())
result = new java.net.URL(result, clsAsResource);
} catch (Exception ex) {
System.out.print("取得路径出错:" + ex.getMessage());
}
}
}
}
if (result == null) {
ClassLoader clsLoader = cls.getClassLoader();
result = clsLoader != null ? clsLoader.getResource(clsAsResource)
: ClassLoader.getSystemResource(clsAsResource);
}
return result;
}
/**
* 将"\"转变"/",用于路径转换,可有可无,只是为了好看点
*/
private String pathChange(String befstr) {
StringBuffer afStr = new StringBuffer();
for (int i = 0; i < befstr.length(); i++) {
if ((befstr.charAt(i)) == '\\')
afStr.append(String.valueOf('/'));
else
afStr.append(befstr.substring(i, i + 1));
}
return afStr.toString();
}
}
-------------------------------------