Search your blog

Tuesday, August 10, 2010

How to Internationalization of page in JSF

How to internationalization in JSF

In this week I am writing a blog on internationalization in JSF .It is very use to implement in your jsf project. There are some steps to implement the very important feature.

Step1.
Writing some properties file for your language required. Properties file is a key-value.
Messages_en.properties as follows:

welcome =Welcome on this site.
login = Enter Number.

Messages_fr.properties as follows:

welcome =Bienvenu Sur MyCV
login =Entrée membre.

We have to save these properties file into source folder in com.messageresource package
Step2.
Configure faces-config.xml file::

< application>
< locale-config>
< default-locale>en< /default-locale>
< supported-locale>fr< /supported-locale>
< /locale-config>
< message-bundle>
com.messageresource.Messages
< /message-bundle>
< /application>

Managed bean configure::

< managed-bean>
< managed-bean-name> localeBean < /managed-bean-name>
< managed-bean-class>com.locale. LocaleBean < /managed-bean-class>
< managed-bean-scope>request< /managed-bean-scope>
< /managed-bean>

Step 3

Create a JavaBean class to hold current instance value from FacesContext and set value into context using setLocale() metheod .

public class LocaleBean {

private HashMap< String, Locale> locales = null;

public LocaleBean() {
locales = new HashMap< String, Locale>(2);
locales.put("english", new Locale("en", "UK"));
locales.put("french", new Locale("fr", "FR"));
}

public void onChooseLocale(ActionEvent event) {
String current = event.getComponent().getId();
FacesContext context = FacesContext.getCurrentInstance();
context.getViewRoot().setLocale((Locale) locales.get(current));
}

}


Step 4
Create a .jspx page for change language of page. Here I am using command link to select language::

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

< f:view>
< f:loadBundle basename="Messages" var="msg"/>
< !DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
< html>
< head>
< meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
< title>welcome Page< /title>

< /head>
< body>
< h:form >
< div class="pageTitle">< h:outputText value="#{msg.welcome}"/>< /div>
< br/>
< h:panelGrid columns="3"
styleClass="center"
style="border:2px solid black"
headerClass="tableHeader">

< h:outputText value="#{msg.login}"/>

< h:commandLink id="english" action="chooseLocale"
actionListener="#{localeBean.onChooseLocale}">
< h:outputText value="#{msg.english}" />
< /h:commandLink>
< h:outputText value=" "/>
< h:commandLink id="french" action="chooseLocale"
actionListener="#{localeBean.onChooseLocale}">
< h:outputText value="#{msg.french}" />
< /h:commandLink>
< /h:panelGrid>
< /h:form>
< /body>
< /html>
< /f:view>