ExternalContext#getResourceAsStream()返回null,将资源文件放置在哪里? [英] ExternalContext#getResourceAsStream() returns null, where to place the resource file?

查看:162
本文介绍了ExternalContext#getResourceAsStream()返回null,将资源文件放置在哪里?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在托管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资源.它不会返回磁盘文件系统资源,因为您需要

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.
 :

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆