一、war包中的文件的讀取
在開(kāi)發(fā)J2EE Web應(yīng)用時(shí),在開(kāi)發(fā)階段通常采用目錄的部署方式,而在正式運(yùn)行時(shí)通常把web應(yīng)用打包為單個(gè)的.war文件進(jìn)行方便地部署。也就是在你的應(yīng)用目錄(比如WebLogic的DefaultWebApp)下,執(zhí)行下面的命令:
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文件的真實(shí)路徑,Log4J通過(guò)文件IO讀取這個(gè)配置文件,完成初始化。
現(xiàn)在一切正常!測(cè)試通過(guò)后,將DefaultWebApp下的所有文件打?yàn)橐粋€(gè).war包,進(jìn)行部署時(shí),發(fā)現(xiàn)系統(tǒng)報(bào)告找不到“D:/bea/wlserver6.1/null/ WEB-INF /log4j.properties”文件!假如你的應(yīng)用中還需要讀取其它已經(jīng)被打包到war包中的文件,都會(huì)報(bào)告找不到文件。并且,系統(tǒng)并不會(huì)到D:/bea/wlserver6.1/config/mydomain/applications/DefaultWebApp目錄下尋找,而會(huì)到D:/bea/wlserver6.1/null下尋找。這是因?yàn)閏ontext.getRealPath("/")返回了null。
查看ServletContext的API文檔,原來(lái),對(duì)一個(gè)打包的應(yīng)用來(lái)說(shuō),是沒(méi)有RealPath的概念的,調(diào)用getRealPath只會(huì)簡(jiǎn)單地返回null。其實(shí),也很好理解,一個(gè)文件被打包入了.war文件,就不存在目錄結(jié)構(gòu)了(雖然包中仍然存在目錄結(jié)構(gòu),但這不等同于文件系統(tǒng)中的目錄結(jié)構(gòu))。
所以,對(duì)war包中的資源是無(wú)法得到RealPath的。這樣也就無(wú)從通過(guò)文件IO進(jìn)行讀取了。那么,如何讀取war包中的資源呢?答案是使用ServletContext.getResourceAsStream(String)方法。對(duì)于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);
那么,現(xiàn)在對(duì)于war應(yīng)用可以成功運(yùn)行,但假如現(xiàn)在不通過(guò)war部署,直接通過(guò)目錄結(jié)構(gòu)部署應(yīng)用會(huì)不會(huì)又出現(xiàn)找不到資源的錯(cuò)誤呢?請(qǐng)來(lái)看看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.
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注