如何获取JSF类中资源的句柄? [英] How to get handle to a resource within a JSF class?
问题描述
我已经在我的JSF项目的src/main/resources
中放置了一个属性文件.
I've put a properties file within src/main/resources
in my JSF project.
如何处理?我知道EL在支持bean中不起作用.
How do I get a handle to it? I understand that EL doesn't work within a backing bean.
注意:该文件位于src/main/resources
中-不在src/main/webapps/resources
中,因此以下内容不起作用:
Note: The file is in src/main/resources
- NOT src/main/webapps/resources
, so the following doesn't work:
FacesContext context = FacesContext.getCurrentInstance();
File value = context.getApplication().evaluateExpressionGet(context, "#{resource['resources:email.properties']}", File.class);
推荐答案
It's thus in the classpath. You can just use ClassLoader#getResourceAsStream()
to get an InputStream
out of it. Assuming that src
is the classpath root and that main/resources
is the package:
InputStream input = Thread.currentThread().getContextClassLoader().getResourceAsStream("main/resources/foo.properties");
Properties properties = new Properties();
properties.load(input);
// ...
或者,如果它是特定于Web应用程序的,因此不应被类路径中具有更高类加载优先级的其他路径(例如,在appserver的lib或JRE的lib中)的同一路径上的文件覆盖,然后使用 ExternalContext#getResourceAsStream()
.
Alternatively, if it's supposed to be specific to the webapp and thus isn't supposed to be overrideable by a file on the same path elsewhere in the classpath which has a higher classloading precedence (e.g. in appserver's lib or the JRE's lib), then use ExternalContext#getResourceAsStream()
instead.
InputStream input = FacesContext.getCurrentInstance().getExternalContext().getResourceAsStream("main/resources/foo.properties");
Properties properties = new Properties();
properties.load(input);
// ...
对于#{resource}
语法,确实确实是针对放置在公共Web内容的/resources
文件夹中的CSS/JS/image资源.另请参见如何在Facelets模板?
As to the #{resource}
syntax, this is indeed specifically for CSS/JS/image resources placed in /resources
folder of public web content. See also How to reference CSS / JS / image resource in Facelets template?
这篇关于如何获取JSF类中资源的句柄?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!