首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > Web前端 >

在weblogic 11g下 this.getServletContext().getRealPath("/")为null的原因及解决办法

2012-08-27 
在weblogic 11g上 this.getServletContext().getRealPath(/)为null的原因及解决方法程序中的很多地方需

在weblogic 11g上 this.getServletContext().getRealPath("/")为null的原因及解决方法

      程序中的很多地方需要用到request.getRealPath()或者getServletContext.getRealPath()。这个方法受到war 和non-war的影响,以及不同app server实现的影响,返回的结果往往不一样,在weblogic中会返回null。?一般的应用都会有一个或几个配置文件放在web-inf下面,getRealPaht返回null是读配置文件有很大困难。
/** * 通过上下文来取工程路径 *  * @return * @throws Exception */private String getAbsolutePathByContext() throws Exception {String webPath = this.getServletContext().getRealPath("/");webPath = webPath.replaceAll("[\\\\\\/]WEB-INF[\\\\\\/]classes[\\\\\\/]?", "/");webPath = webPath.replaceAll("[\\\\\\/]+", "/");webPath = webPath.replaceAll("%20", " ");if (webPath.matches("^[a-zA-Z]:.*?$")) {} else {webPath = "/" + webPath;}webPath += "/";webPath = webPath.replaceAll("[\\\\\\/]+", "/");return webPath;}/** * 通过类路径来取工程路径 *  * @return * @throws Exception */private String getAbsolutePathByClass() throws Exception {String webPath = this.getClass().getResource("/").getPath().replaceAll("^\\/", "");webPath = webPath.replaceAll("[\\\\\\/]WEB-INF[\\\\\\/]classes[\\\\\\/]?", "/");webPath = webPath.replaceAll("[\\\\\\/]+", "/");webPath = webPath.replaceAll("%20", " ");if (webPath.matches("^[a-zA-Z]:.*?$")) {} else {webPath = "/" + webPath;}webPath += "/";webPath = webPath.replaceAll("[\\\\\\/]+", "/");return webPath;}private String getAbsolutePathByResource() throws Exception {URL url = this.getServletContext().getResource("/");String path = new File(url.toURI()).getAbsolutePath();        if (!path.endsWith("\") && !path.endsWith("/")) {path += File.separator;}return path;}public String init() throws ServletException {String webPath = null;try {webPath = getAbsolutePathByContext();} catch (Exception e) {}// 在weblogic 11g 上可能无法从上下文取到工程物理路径,所以改为下面的if (webPath == null) {try {webPath = getAbsolutePathByClass();} catch (Exception e) {}}if (webPath == null) {try {webPath = getAbsolutePathByResource();} catch (Exception e) {}}System.out.println(webPath);return webPath;}

??在weblogic里面war通过getAbsolutePathByContext()方法获取路径为空?,是很正常的
??对一个打包的应用来说,是没有RealPath的概念的,调用getRealPath只会简单地返回null

所以可以通过上面的通过类路径来取工程路径

热点排行