我已在 JSF 项目的 src/main/resources
中放置了一个属性文件。
我如何获得它的句柄?据我所知,EL 无法在支持 bean 中工作。
注意:该文件位于 src/main/resources
中,而不是 src/main/webapps/resources
中,因此以下内容不会工作:
FacesContext context = FacesContext.getCurrentInstance();
File value = context.getApplication().evaluateExpressionGet(context, "#{resource['resources:email.properties']}", File.class);
最佳答案
因此它位于类路径中。您可以使用 ClassLoader#getResourceAsStream()
从中获取一个InputStream
。假设 src 是类路径根,而 main/resources 是包:
InputStream input = Thread.currentThread().getContextClassLoader().getResourceAsStream("main/resources/foo.properties");
Properties properties = new Properties();
properties.load(input);
// ...
或者,如果它应该特定于 web 应用程序,因此不应该被类路径中其他位置的同一路径上的文件覆盖,该文件具有更高的类加载优先级(例如在应用程序服务器的 lib 或 JRE 的 lib 中) ,然后使用ExternalContext#getResourceAsStream()
相反。
InputStream input = FacesContext.getCurrentInstance().getExternalContext().getResourceAsStream("main/resources/foo.properties");
Properties properties = new Properties();
properties.load(input);
// ...
对于#{resource}
语法,这确实是专门针对放置在公共(public)网页内容的/resources
文件夹中的CSS/JS/图像资源的。另请参阅How to reference CSS / JS / image resource in Facelets template?
关于jsf - 如何获取 JSF 类中资源的句柄?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10590003/