vineri, 31 iulie 2009

JSF Localization

Localizations is the process through which an application(web or desktop) can present its' content in multiple languages. This is a hot subject nowadays and a standard is not yet defined for how to properly implement localization. In Java/JSF we can use ResourceBundle class from java.util. A simple example is shown below.

1. We create two resource files(english and romanian).
In each of them we add lbWelcome key with english(romanian) text.

2. We modify faces-config.xml for indicating the supported languages.

<application>
<locale-config>
<default-locale>ro< /default-locale>
<supported-locale>ro< /supported-locale>
<supported-locale>en< /supported-locale>
</ locale-config>
</application>

3. We create a jsp page for presenting the content.

<%@page pageEncoding="UTF-8" contentType="text/html; charset=ISO-8859-2" %>
<%@taglib prefix="f" uri="http://java.sun.com/jsf/core" %>
<%@taglib prefix="h" uri="http://java.sun.com/jsf/html" %>

<f:view>


<h:form>
<h:commandLink action="#{languageBean.changeLanguage}" value="Romana">
<f:param name="lang" value="ro">
</h:commandLink>
|
<h:commandLink action="#{languageBean.changeLanguage}" value="English">
<f:param name="lang" value="en">
</h:commandLink><>

<h:outputText value="#{msg.lbWelcome}">
</h:form>
</f:view>

4. We create a backbean in which the method for changing the language is implemented


package ro.testlocalization.traduceri;

import java.util.Locale;
import java.util.Map;

import javax.faces.application.Application;
import javax.faces.application.ViewHandler;
import javax.faces.component.UIViewRoot;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;

public class LanguageBean {
public void changeLanguage() {
Map req = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
String lang = req.get("lang").toString();

Locale newLocale = new Locale(lang);
FacesContext context = FacesContext.getCurrentInstance();
context.getViewRoot().setLocale(newLocale);
}
}

5. We map the backbean in faces-config.xml.

Niciun comentariu:

Trimiteți un comentariu