How to get a JSF resource bundle property value in backing bean?
Asked Answered
J

2

11

I am using JSF 2. I am trying to resolve a message bundle reference dynamically the a managed bean property. The value contains the bundle name as well as the key. This is required as the value may come from one of a few different bundles. I have tried many permutations, but the value from the bean seems to be always resolved as a literal String (outputting with EL brackets) and the bundle is never called to resolve and return the value. Any ideas?

I have tried:

#{bundle['key']}
${bundle['key']}
bundle['key']

They are outputted exactly as-is, also in a <h:outputText>. It works fine if I write it directly in the page. My theory is that JSF doesnt realise it has to process the String as an expression. Is there some way to force it?

Jobi answered 24/2, 2012 at 15:32 Comment(0)
B
19

EL will only be resolved in the view, not in the model. It would otherwise be a huge EL injection attack hole which allows endusers to enter arbitrary EL expressions in input fields and have them resolved. No, you cannot force it in any way.

You need to resolve it yourself. You can do that by either evaluating it programmatically using Application#evaluateExpressionGet():

FacesContext context = FacesContext.getCurrentInstance();
String value = context.getApplication().evaluateExpressionGet(context, "#{bundle['key']}", String.class);
// ...

Or, in this particular case, by just using the ResourceBundle API directly like as JSF is doing under the covers:

ResourceBundle bundle = ResourceBundle.getBundle(basename, FacesContext.getCurrentInstance().getViewRoot().getLocale());
String value = bundle.getString("key");
// ...
Blanchard answered 24/2, 2012 at 16:39 Comment(1)
Thank you BalusC for your prompt and helpful response, this has answered my question.Jobi
C
1

Try this..

Resource Bundle referenced by msg

USD=$

xhtml code:

<c:set var="key" value="#{managedBean.currencyCode}" />
<h:outputText value="#{msg[key]}"/>

This should work..

Chesty answered 18/3, 2015 at 22:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.