How can I get a message bundle string from inside a managed bean?

后端 未结 3 1270
情话喂你
情话喂你 2020-12-01 06:38

I would like to be able to retrieve a string from a message bundle from inside a JSF 2 managed bean. This would be done in situations where the string is used as the summary

相关标签:
3条回答
  • 2020-12-01 06:47

    There are two ways to get String resource bundle in managed bean, using baseName or varName (see definition of each one below):

    Using varName:

    varName: is the String representing the <var></var> in <resource-bundle>

    FacesContext context = FacesContext.getCurrentInstance();
    Application app = context.getApplication();
    ResourceBundle bundle = app.getResourceBundle(context, varName);
    String msg = bundle.getString("key");
    

    Using baseName:

    baseName: The fully qualified name of the resource bundle (<base-name> in <resource-bundle>).

    FacesContext context = FacesContext.getCurrentInstance();
    Locale locale = context .getViewRoot().getLocale();
    ClassLoader loader = Thread.currentThread().getContextClassLoader();
    ResourceBundle bundle = ResourceBundle.getBundle(baseName, locale, loader);
    String msg = bundle.getString("key");
    
    0 讨论(0)
  • 2020-12-01 07:07

    You can get the full qualified bundle name of <message-bundle> by Application#getMessageBundle(). You can get the current locale by UIViewRoot#getLocale(). You can get a ResourceBundle out of a full qualified bundle name and the locale by ResourceBundle#getBundle().

    So, summarized:

    FacesContext facesContext = FacesContext.getCurrentInstance();
    String messageBundleName = facesContext.getApplication().getMessageBundle();
    Locale locale = facesContext.getViewRoot().getLocale();
    ResourceBundle bundle = ResourceBundle.getBundle(messageBundleName, locale);
    // ...
    

    Update: as per the mistake in the question, you actually want to get the bundle which is identified by the <base-name> of <resource-bundle>. This is unfortunately not directly available by a standard JSF API. You've either to hardcode the same base name in the code and substitute the messageBundleName in the above example with it, or to inject it as a managed property on <var> in a request scoped bean:

    @ManagedProperty("#{msg}")
    private ResourceBundle bundle; // +setter
    
    0 讨论(0)
  • 2020-12-01 07:09
    FacesContext context = FacesContext.getCurrentInstance();
    ResourceBundle bundle = context.getApplication().getResourceBundle(context, "msg");
    String message = bundle.getString("key");
    

    here is key is property name which you want to access from properties file .

           message = This is "message"
    

    This entry is from messages.properites file. and "message" is "key" .

    0 讨论(0)
提交回复
热议问题