jsf - 如何获取 JSF 类中资源的句柄?

标签 jsf properties resources classpath

我已在 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/

相关文章:

java - Primefaces 登录应用程序

java - 将属性转换为输入流?

java - 如何在Tomcat中获取属性文件

java - 通过从另一个文件逐行读取来加载属性文件

winapi - 如何知道 Windows 上的子进程状态和资源使用情况?

arrays - 集合/数组包含方法

jsf - org.jboss.weld.exceptions.WeldException : WELD-000049: Unable to invoke private void init()

java - "isUserInRole"方法与JAAS相关吗?

将任务分配给资源的算法

c# - 如何从我的项目中删除不必要的资源?