问题
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