Friday, June 13, 2008

JSF Internnationalization

In faces-config.xml
<application>
<message-bundle>messages</message-bundle>
</application>
Let's say your browser Language Preference is "zh-cn, en-us", it will look up properties files in the sequece below
  • messages_zh-cn.properties
  • messages_en-us.properties
  • messages.properties

If the language is non-Latin 1(ISO-8859-1) and non-Unicode, you need convert the properties file by native2ascii. Here is a sample of how to use native2ascii
native2ascii -encoding GBK messages_zh-cn.txt messages_zh-cn.properties


Set locale in faces-config.xml
<faces-config>
<application>
<local-config>
<default-locale>en</default-locale>
<supported-locale>zh-cn</supported-locale>
</local-config>
</application>
.....
</faces-config>


Set locale property of in the page
<f:view locale="zh-cn">
<f:loadBundle basename="messages" var="msgs"/>
Or set locale property with the value of a variable, which could come from cookie, database or whatever...
<f:view locale="#{user.locale}">
<f:loadBundle basename="messages" var="msgs"/>


To refer to the message in page, see the sample below
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<%@page contentType="text/html;charset=UTF-8"%>

<f:view>
<f:loadBundle basename="messages" var="msgs"/>

<html>
<head>
<title><h:outputText value="#{msgs.titleText}"/></title>
</head>
<body>

<h:form>
<h3><h:outputText value="#{msgs.hintText}"/></h3>
<h:outputText value="#{msgs.nameText}"/>:
<h:inputText value="#{user.name}"/><p>
<h:outputText value="#{msgs.passText}"/>:
<h:inputSecret value="#{user.password}"/><p>
<h:commandButton value="#{msgs.commandText}"
actionListener="#{user.verify}"
action="#{user.outcome}"/>
</h:form>

</body>
</html>

</f:view>

No comments:

Post a Comment