JSF 2.2:在 faces 之外配置可用的语言环境-config.xml

JSF 2.2: Configure available Locales outside faces-config.xml

目前我的 faces-config.xml 中有一个部分如下:

    <locale-config>
        <default-locale>en</default-locale>
        <supported-locale>en_US</supported-locale>
        <supported-locale>en_GB</supported-locale>
        <supported-locale>de</supported-locale>
        <supported-locale>de_DE</supported-locale>
    </locale-config>

这是按预期工作的。

问题是,我必须能够定义这些语言环境而无需触及我 war 中的面孔-config.xml。这个想法有例如定义所有可用语言环境的资源路径上的配置文件。

我已经尝试过 programatic approach as well as using a second faces-config.xml in the META-INF of another module i have access to and defining an specific file on the ressource path which should be merged according to this article。在每种情况下,第二个文件都以有效的 faces-config.xml 格式包含上述部分。两者都没有任何影响(既没有错误也没有任何行为变化)

有没有什么好的方法可以在不触及原始 faces-config 的情况下做到这一点?

我能够更改耳模块并在任何位置以编程方式访问资源。不幸的是,在 .war 中调整 faces-config.xml 是没有选择的。

据我所知,这里有一个误解。如果您使用自定义 resolvers/resource bundles/whatever 并且可以完全控制事物,则无需在 locale-config 中配置任何内容。

如果您查看 Add Resource Bundles Programmatically, you see the OmniFaces Faces.getLocale() 中的答案,用于将语言环境传递给 resourceBundle

Locale userLocale = Faces.getLocale();
ResourceBundle b = ResourceBundle.getBundle("msgs", userLocale);

因此,有效的做法是以编程方式选择的区域设置传递给它,而不是自动使用 locale-config 中配置的内容。

事实上 IN Faces.getLocale() 一些代码存在以使用 locale-config 是为了确保当人们在 locale-config 中配置了某些东西时可以使用它,所以它的行为如下预期在普通的普通 JSF 中。在第 16 行中,它检索用户在请求中发送的语言环境。在第 18 行中,它根据 supported-locale(可以在自定义实现中省略!!!)进行检查,如果不匹配,则使用 default-locale(可以省略,第 7 行也可以) 12)

1   /**
2     * {@inheritDoc}
3     * @see Faces#getLocale()
4     */
5   public static Locale getLocale(FacesContext context) {
6       Locale locale = null;
7       UIViewRoot viewRoot = context.getViewRoot();
8
9       // Prefer the locale set in the view.
10      if (viewRoot != null) {
11          locale = viewRoot.getLocale();
12      }
13
14      // Then the client preferred locale.
15      if (locale == null) {
16          Locale clientLocale = context.getExternalContext().getRequestLocale();
17
18          if (getSupportedLocales(context).contains(clientLocale)) {
19              locale = clientLocale;
20          }
21      }
22
23      // Then the JSF default locale.
24      if (locale == null) {
25          locale = context.getApplication().getDefaultLocale();
26      }
27
28      // Finally the system default locale.
29      if (locale == null) {
30          locale = Locale.getDefault();
31      }
32
33      return locale;
34  }

所以这段代码可以完全根据您的喜好进行调整,包括首先检查用户是否在您的应用程序中配置了首选语言环境,否则使用浏览器发送的语言环境(如果支持)。