Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
454 views
in Technique[技术] by (71.8m points)

properties - How to get handle to a resource within a JSF class?

I've put a properties file within src/main/resources in my JSF project.

How do I get a handle to it? I understand that EL doesn't work within a backing bean.

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);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);
// ...

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);
// ...

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...