一、war包中的文件的读取
在开发J2EE Web应用时,在开发阶段通常采用目录的部署方式,而在正式运行时通常把web应用打包为单个的.war文件进行方便地部署。也就是在你的应用目录(比如WebLogic的DefaultWebApp)下,执行下面的命令:
jar cf0 mywebapp.war **
[PRe] --DefaultWebApp --index.jsp --.....jsp --WEB-INF -- web.xml -- log4j.properties -- classes ......[/pre]
ServletContext context = getServletContext(); org.apache.log4j.PropertyConfigurator.configure(context.getRealPath("/")+ "/WEB-INF/log4j.properties");
D:/bea/wlserver6.1/config/mydomain/applications/DefaultWebApp
/bea/wlserver6.1/config/mydomain /applications/DefaultWebApp
"/ WEB-INF /log4j.properties"
拼接后,就得到了log4j.properties文件的真实路径,Log4J通过文件IO读取这个配置文件,完成初始化。
现在一切正常!测试通过后,将DefaultWebApp下的所有文件打为一个.war包,进行部署时,发现系统报告找不到“D:/bea/wlserver6.1/null/ WEB-INF /log4j.properties”文件!假如你的应用中还需要读取其它已经被打包到war包中的文件,都会报告找不到文件。并且,系统并不会到D:/bea/wlserver6.1/config/mydomain/applications/DefaultWebApp目录下寻找,而会到D:/bea/wlserver6.1/null下寻找。这是因为context.getRealPath("/")返回了null。
查看ServletContext的API文档,原来,对一个打包的应用来说,是没有RealPath的概念的,调用getRealPath只会简单地返回null。其实,也很好理解,一个文件被打包入了.war文件,就不存在目录结构了(虽然包中仍然存在目录结构,但这不等同于文件系统中的目录结构)。
所以,对war包中的资源是无法得到RealPath的。这样也就无从通过文件IO进行读取了。那么,如何读取war包中的资源呢?答案是使用ServletContext.getResourceAsStream(String)方法。对于org.apache.log4j.PropertyConfigurator,有如下几种配置方法:
static void configure(Properties properties); static void configure(String configFilename); static void configure(URL configURL);
InputStream is = getServletContext(). getResourceAsStream("/WEB-INF/log4j.properties"); Properties props = new Properties(); try{ props.load(is); }catch (IOException e){ System.err.println("Load log4j configuration failed"); } PropertyConfigurator.configure(props);
那么,现在对于war应用可以成功运行,但假如现在不通过war部署,直接通过目录结构部署应用会不会又出现找不到资源的错误呢?请来看看ServletContext.getResourceAsStream的API文档,
Returns a URL to the resource that is mapped to a specified path. The path must begin with a "/" and is interpretedas relative to the current context root. This method allows the servlet container to make a resource available to servletsfrom any source. Resources can be located on a local or remote file system,in a database, or in a .war file.
新闻热点
疑难解答