ExternalContext#getResourceAsStream() returns null, where to place the resource file?

孤人 提交于 2019-12-06 10:41:27

问题


I'm trying to obtain a PNG file as InputStream in my managed bean as below:

ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
InputStream input = externalContext.getResourceAsStream("/myFile.png");
// input is null.

However, the InputStream is always null. How is this caused and how can I solve it?


回答1:


Apparently you placed the resource in physically the wrong location.

The ExternalContext#getResourceAsStream(), which delegates in case of servlet containers under the covers to ServletContext#getResoruceAsStream(), has its root in the web content of the WAR (the parent folder of /WEB-INF and /META-INF folders, thus the files therein are also available this way), and the /META-INF/resources folder of all JARs in /WEB-INF/lib. In case of a JSF web application it are usually XHTML, CSS, JavaScript and image files.

In other words, it returns web resources. It doesn't return a disk file system resource, for that you need new FileInputStream() instead. It also doesn't return a classpath resource, for that you need ClassLoader#getResourceAsStream() instead. The classpath has its root in a.o. /WEB-INF/classes, all JARs in /WEB-INF/lib, and some VM/server-configured folders depending on the runtime environment.

In an usual web content file structure, the resource file has to be placed exactly here in order to obtain it the desired way:

WebContent
 |-- META-INF
 |-- WEB-INF
 |    |-- faces-config.xml
 |    `-- web.xml
 |-- myFile.png    <-- Here.
 :
  • getResourceAsStream() vs FileInputStream
  • Accessing properties file in a JSF application programmatically
  • Where to place and how to read configuration resource files in servlet based application?
  • How to get the root path of a web project in java EE


来源:https://stackoverflow.com/questions/25784482/externalcontextgetresourceasstream-returns-null-where-to-place-the-resource

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!