JSF 2.0中的国际化

mak*_*aks 6 internationalization jsf-2

我想知道国际化在jsf中是如何运作的?我已经在coreservlets.com上阅读了关于它的教程,但就我而言,它的工作方式略有不同.在那个教程中说我必须使用

FacesContext.getCurrentInstance().getViewRoot().setLocale(newLocale);
Run Code Online (Sandbox Code Playgroud)

in actionListener(更改语言环境的监听器)以及支持bean必须具有getCurrentLocale()<f:view>标记中使用它的属性.

我有2个带有消息的属性文件(默认和具有指定的语言环境),它们已注册faces-config.xml.<f:view>标签我只有一页(index.xhtml)

<f:view locale="#{bean.locale}">
...
</f:view>
Run Code Online (Sandbox Code Playgroud)

我还为每个语言环境提供了2个按钮(带有actionListener).在支持bean中,我只需修改当前的语言环境变量(不要使用getViewRoot().setLocale(newLocale)).但所有页面的区域设置都会更改(即使它们没有<f:view locale="#{bean.locale}">)

Sha*_*zeb 23

假设您有以下两个消息文件

    messages.properties
    messages_de.properties
Run Code Online (Sandbox Code Playgroud)

设置应用程序区域设置
有三种设置应用程序区域设置的方法,我认为您需要第一个方法.

1 - 您可以让浏览器选择区域设置.

在中设置默认和支持的区域设置 WEB-INF/faces-config.xml:

<faces-config>
   <application>
      <locale-config>
         <default-locale>en</default-locale>
         <supported-locale>de</supported-locale>
      </locale-config>
  </application>
</faces-config>
Run Code Online (Sandbox Code Playgroud)

当浏览器连接到您的应用程序时,它通常在HTTP标头中包含Accept-Language值

2 - 您可以以编程方式设置区域设置.

调用UIViewRoot对象的setLocale方法:

UIViewRoot viewRoot = FacesContext.getCurrentInstance().getViewRoot();
viewRoot.setLocale(new Locale("de"));
Run Code Online (Sandbox Code Playgroud)

3 - 您可以为单个页面设置区域设置
通过使用f:view具有区域设置属性的元素 - 例如:

<f:view locale="de">
Run Code Online (Sandbox Code Playgroud)

可以动态设置区域设置:

<f:view locale="#{user.locale}"/>
Run Code Online (Sandbox Code Playgroud)


声明消息包
现在已设置了Locale,您可以使用以下两种方法之一来声明消息包

1-Via faces-config 最简单的方法是在应用程序的WEB-INF目录中提供名为faces-config.xml的文件,其中包含以下内容:

<?xml version="1.0"?>
<faces-config xmlns="http://java.sun.com/xml/ns/javaee"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
      http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd"
   version="2.0">
   <application>
      <resource-bundle>
         <base-name>com.corejsf.messages</base-name>
         <var>msgs</var>
      </resource-bundle>
   </application>
</faces-config>
Run Code Online (Sandbox Code Playgroud)

2 - 在需要访问它的每个JSF页面上. 您可以将f:loadBundle元素添加到需要访问该bundle的每个JSF页面,而不是使用全局资源包声明,如下所示:

<f:loadBundle basename="com.corejsf.messages" var="msgs"/>
Run Code Online (Sandbox Code Playgroud)

在任何一种情况下,bundle中的消息都可以通过名为msgs的map变量访问.

在按钮上显示适当的标签 现在让我们说默认属性文件,即英语有属性

next=Next
Run Code Online (Sandbox Code Playgroud)

和德语有等价的

next=Weiter
Run Code Online (Sandbox Code Playgroud)

并且您已设置了语言环境并声明了mesg包,您可以访问它以将标签放在命令按钮上

<h:commandButton value="#{msgs.next}"/>
Run Code Online (Sandbox Code Playgroud)

上面的答案是从Hortsmen Core Java Server Faces一书中提取和修改的.