当前位置: 代码迷 >> Web前端 >> 在weblogic 11g下 this.getServletContext().getRealPath("/")为null的原因及解决办法
  详细解决方案

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

热度:847   发布时间:2012-08-27 21:21:57.0
在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

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

  相关解决方案