解決weblogic中的getRealPath()問題

程序中的很多地方需要用到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可能不是最終的答案(一般來說前面多了一個/),需要你根據實際情況去加工一下。
至此問題全部解決。
發佈了45 篇原創文章 · 獲贊 0 · 訪問量 2407
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章