ExternalContext#getResourceAsStream()返回null,将资源文件放置在哪里? [英] ExternalContext#getResourceAsStream() returns null, where to place the resource file?
问题描述
我正在尝试在托管bean中以InputStream
的形式获取PNG文件,如下所示:
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.
但是,InputStream
始终为空.这是怎么引起的,我该如何解决?
However, the InputStream
is always null. How is this caused and how can I solve it?
推荐答案
显然您将资源放置在错误的位置.
Apparently you placed the resource in physically the wrong location.
ExternalContext#getResourceAsStream()
,如果是servlet容器,则将其委托给
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.
换句话说,它返回Web资源.它不会返回磁盘文件系统资源,因为您需要 ClassLoader#getResourceAsStream()
代替.类路径的根源是a.o. /WEB-INF/classes
,/WEB-INF/lib
中的所有JAR,以及某些VM/服务器配置的文件夹,具体取决于运行时环境.
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.
在通常的Web内容文件结构中,必须将资源文件准确放置在此处,以便以所需的方式获取它:
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()与FileInputStream
- 在JSF应用程序中以编程方式访问属性文件
- 在何处放置以及如何放置在基于servlet的应用程序中读取配置资源文件?
- 如何获取Java EE中的Web项目的根路径
- 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
这篇关于ExternalContext#getResourceAsStream()返回null,将资源文件放置在哪里?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!