gpt4 book ai didi

jsf - 如何从托管bean中获取消息捆绑字符串?

转载 作者:行者123 更新时间:2023-12-03 08:51:22 26 4
gpt4 key购买 nike

我希望能够从JSF 2托管bean内部的消息束中检索字符串。在将字符串用作FacesMessage中的summary或​​details参数或在引发的异常中用作消息的情况下,可以这样做。

我想确保托管bean为用户的语言环境加载正确的消息束。我不清楚如何使用JSF API调用从托管Bean中执行此操作。

我的配置是:

  • 使用Tomcat 7作为容器,因此解决方案不能依赖仅在完整的应用程序服务器容器中工作的API调用
  • 使用JSF 2引用实现(Mojarra)
  • 不使用任何允许CDI的库

  • 注意:我确实看到了 this similar question,但这取​​决于我的配置中不可用的功能

    编辑:我在原始问题中犯了一个错误。我要问的是“如何从托管bean中获取 资源 bundle 字符串”? BalusC给了我正确答案。我实际上要问的问题的解决方案非常相似:
    public static String getResourceBundleString(
    String resourceBundleName,
    String resourceBundleKey)
    throws MissingResourceException {
    FacesContext facesContext = FacesContext.getCurrentInstance();
    ResourceBundle bundle =
    facesContext.getApplication().getResourceBundle(
    facesContext, resourceBundleName);
    return bundle.getString(resourceBundleKey);
    }

    另外,这是 another question的链接,该链接解释了“消息” bundle 包和“资源” bundle 包之间的区别。

    最佳答案

    您可以通过 <message-bundle> 获得Application#getMessageBundle()的完整合格 bundle 包名称。您可以通过 UIViewRoot#getLocale() 获取当前语言环境。您可以从完全合格的 bundle 包中获取ResourceBundle名称和语言环境(由 ResourceBundle#getBundle() 决定)。

    因此,总结为:

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

    更新:根据问题中的错误,您实际上想要获取由 <base-name><resource-bundle>标识的 bundle 包。遗憾的是,标准JSF API无法直接使用此功能。您必须在代码中对相同的基本名称进行硬编码,并用上面的示例替换 messageBundleName,或者将其作为托管属性插入到请求范围内的Bean中的 <var>上:
    @ManagedProperty("#{msg}")
    private ResourceBundle bundle; // +setter

    关于jsf - 如何从托管bean中获取消息捆绑字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6272945/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com