JSF 2 localization (managed bean)

前端 未结 5 1582
生来不讨喜
生来不讨喜 2020-12-24 04:23

I have a properties file for localization:

foo=Bar
title=Widget Application

This is tied in as a resource-bundle in the face

5条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-24 04:37

    You can do this with JSF alone.

    Start by defining a managed property on your backing bean. In the JSF configuration, you can set the managed property's value to an EL expression that references your resource bundle.

    I've done something like the following using Tomcat 6. The only caveat is that you can't access this value from your backing bean's constructor, since JSF will not yet have initialized it. Use @PostConstruct on an initialization method if the value is needed early in the bean's lifecycle.

    
      ...
      
        messages
        java.util.ResourceBundle
        #{msgs}
      
      ...
    
    
    
      ...
      
        com.example.messages.messages
        msgs
      
      ...
    
    

    This has the advantage of making your backing bean methods less dependent on the presentation technology, so it should be easier to test. It also decouples your code from details like the name given to the bundle.

    Some testing using Mojarra 2.0.4-b09 does show a small inconsistency when a user changes locale mid-session. In-page EL expressions use the new locale but the backing bean isn't given the new ResourceBundle reference. To make it consistent you could use the bean property value in EL expressions, such as using #{backingBean.messages.greeting} in place of #{msgs.greeting}. Then page EL and the backing bean would always use the locale that was active when the session began. If users had to switch locales mid-session and get the new messages, you could try making a request-scoped bean and give it references to both the session bean and resource bundle.

提交回复
热议问题