1

I have a Problem with jsf and multiple languages. So my strings are in WEB_INF/classes/texte_<lang>.properties files. And are accessed for example like that <h:outputLabel value="#{messages.err_text}"/> which works fine.

The problem is, i have <h:outputLabel... element where i want to show an error message depending on the error. I would like something that works like this:

<h:outputLabel value="#{someBean.errMsg}/>

With a Bean like that

@ManagedBean()
@SessionScoped
public class SomeBean{
  public String getErrMsg(){
     if(something){
      return "#{messages.err_text}" 
     }else if(somethingElse){
      return "#{messages.err_text2}" 
     }else{
      return "#{messages.err_text3}" 
     }
  }
}

Just to be clear it doesn't work that way. I'm looking for a similar solution (or any solution) that works.
Thanks for reading.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
AntJOo
  • 13
  • 3

2 Answers2

1

Don't do it that way. The model shouldn't be aware of the view. Localization also doesn't strictly belong in the model. The model should instead prepare some state which the view has to be aware of.

One way would be:

public String getErrMsg(){
    if (something) {
        return "err_text";
    } else if (somethingElse) {
        return "err_text2";
    } else {
        return "err_text3";
    }
}
<h:outputLabel value="#{messages[someBean.errMsg]}" />

Other way would be returning an enum as demonstrated in the following related questions: Localizing enum values in resource bundle and How to use enum values in f:selectItem(s).

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
0

The reason why what you have now is not working, is because the value attribute of the outputText is evaluated as a plain String, and not as an EL expression.

Going by what you are working with now, the best way to proceed is to inject the resource bundle directly into your bean:

@ManagedProperty("#{messages}")
ResourceBundle messages;

And then,

public String getErrMsg(){
   if(something){
      messages.getString("err_text");
   }
}

In case you're not aware, traditionally, error messages are presented using the h:message component.


On an unrelated note to your original question, you should also know that it's not generally advisable to have processing logic buried in your getter. For one thing, the getter is called multiple times during the rendering of your page. Also for this to work properly, you should be able to guarantee that the value something will stay consistent across the entire lifecycle of a single JSF request

kolossus
  • 20,559
  • 3
  • 52
  • 104