程序中的很多地方需要用到request.getRealPath()或者getServletContext.getRealPath()。这个方法受到war 和non-war的影响,以及不同app server实现的影响,返回的结果往往不一样,在weblogic中会返回null。
一般的应用都会有一个或几个配置文件放在web-inf下面,getRealPaht返回null是读配置文件有很大困难。解决方法是使用getServletContext().getResourceAsStream.示例如下:
InputStream is = getServletContext().getResourceAsStream("/WEB-INF/config.properties");
Properties props = new Properties();
try {
props.load(is);
} catch (IOException e) {
System.err.println("Load configuration failed");
}
PropertyConfigurator.configure(props);
上面方法并没有解决根本问题,根本问题就是得到RealPath,可以使用下面方法得到RealPath:
try {
URL u = getServletContext().getResource("/");
String weblogic_path=u.getPath();
} catch (MalformedURLException e) {
e.printStackTrace();
}
这个语句得到的RealPath可能不是最终的答案(一般来说前面多了一个/),需要你根据实际情况去加工一下。
至此问题全部解决。
一般的应用都会有一个或几个配置文件放在web-inf下面,getRealPaht返回null是读配置文件有很大困难。解决方法是使用getServletContext().getResourceAsStream.示例如下:
InputStream is = getServletContext().getResourceAsStream("/WEB-INF/config.properties");
Properties props = new Properties();
try {
props.load(is);
} catch (IOException e) {
System.err.println("Load configuration failed");
}
PropertyConfigurator.configure(props);
上面方法并没有解决根本问题,根本问题就是得到RealPath,可以使用下面方法得到RealPath:
try {
URL u = getServletContext().getResource("/");
String weblogic_path=u.getPath();
} catch (MalformedURLException e) {
e.printStackTrace();
}
这个语句得到的RealPath可能不是最终的答案(一般来说前面多了一个/),需要你根据实际情况去加工一下。
至此问题全部解决。
解决WebLogic中获取真实路径问题
本文介绍了解决在WebLogic服务器环境下使用request.getRealPath()返回null的问题,提供了通过getServletContext().getResourceAsStream()读取配置文件的方法,并给出获取真实路径的解决方案。
380

被折叠的 条评论
为什么被折叠?



