[英]ExternalContext#getResourceAsStream() returns null, where to place the resource file?
I'm trying to obtain a PNG file as InputStream
in my managed bean as below: 我正在尝试在托管bean中获取PNG文件作为
InputStream
,如下所示:
ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
InputStream input = externalContext.getResourceAsStream("/myFile.png");
// input is null.
However, the InputStream
is always null. 但是,
InputStream
始终为null。 How is this caused and how can I solve it? 这是怎么引起的,我该如何解决?
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
. ExternalContext#getResourceAsStream()
在Servlet容器的情况下将其委托给ServletContext#getResoruceAsStream()
,其根位于WAR的Web内容中( /WEB-INF
和/META-INF
文件夹的父文件夹,因此,其中的文件也可以通过这种方式获得),以及/WEB-INF/lib
中所有JAR的/META-INF/resources
文件夹。 In case of a JSF web application it are usually XHTML, CSS, JavaScript and image files. 对于JSF Web应用程序,通常是XHTML,CSS,JavaScript和图像文件。
In other words, it returns web resources. 换句话说,它返回Web资源。 It doesn't return a disk file system resource, for that you need
new FileInputStream()
instead. 它不会返回磁盘文件系统资源,因为您需要
new FileInputStream()
。 It also doesn't return a classpath resource, for that you need ClassLoader#getResourceAsStream()
instead. 它还不会返回类路径资源,因为您需要
ClassLoader#getResourceAsStream()
。 The classpath has its root in ao /WEB-INF/classes
, all JARs in /WEB-INF/lib
, and some VM/server-configured folders depending on the runtime environment. 类路径的根源于
/WEB-INF/classes
,所有JAR位于/WEB-INF/lib
,并且某些VM / server配置的文件夹取决于运行时环境。
In an usual web content file structure, the resource file has to be placed exactly here in order to obtain it the desired way: 在通常的Web内容文件结构中,必须将资源文件准确放置在此处,以便以所需的方式获取它:
WebContent
|-- META-INF
|-- WEB-INF
| |-- faces-config.xml
| `-- web.xml
|-- myFile.png <-- Here.
:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.