Internationalization in JSF


<< Previous        Next >>


Internationalization in JSF 


Internationalization and Localization are important features for a web based application. Often the term i18n and L10n is encountered in the context of internationalization and localization. . The abbreviation is based on the fact that the rather lengthy word 'internationalization' starts with an 'i' followed by 18 characters followed by an 'n'. L10n follow the same logic as i18n. An application that has been internationalized can be localized for different regions without changing any code.

The overall effect of implementing localization, is that our application will conform dynamically to the language, number and time formats defined by a particular locale.

Creating an internationalized application comes in two steps:
  • Internationalization: Implementing the features in your application to support multiple languages
  • Localization: Presenting text, graphic, date, currency etc specific to a region 
An internationalized program is designed so that items such as status messages, GUI component labels, currency, date etc should not be hardcoded in the program instead they should be stored outside the source code in resource bundles and retrieved dynamically. Localization is the process of translating these items to a particular language and adding any locale-specific components.

For eg:Number formats and date formats vary — not just by language, but by country too. In US, commas are used for millions and thousands, and a period for the decimal point, as in “72,350.55”. But the convention in Germany is precisely the opposite: “72.350,55”. Even countries that share the same language may differ on conventional formats. Americans tend to write dates as MM/DD/YY, but British write DD/MM/YY. Localizing a user interface requires knowing about the cultural associations attached to symbols or colors, and making sure you don’t send the wrong message. In East Asia, particularly China, white is associated with death, and is used as a color theme for funerals. In the West, on the other hand, white is a symbol of purity, and brides wear white at their weddings.

An internationalized program can display information differently throughout the world.It references a Locale object of the java.util.Locale class to identify the appropriate language and region of its end users.

Localization needs to be specified by a language/country pair, also called a locale. A local represents a language and country combination, like de_DE or en_US. The language codes are lowercase, two-letter strings defined by the International Organization for Standardization (ISO) and the country codes are uppercase, two-letter strings, also defined by ISO. The country code is optional, so en alone is a valid locale string for the English language, regardless of country. If you want to have different message resource files for English in the U.K. and English in the USA, you have to add the country code (en_GB, en_US).

Let’s add internationalization features to our application and then localize it to one or more different languages (e.g. English, Spanish, and French.)

In last section we have moved all text that must be localized to property files (messages.properties)that serve as resource bundle. Now we have to provide resource bundle (property file) for each language we plan to support. (e.g. English , Spanish, and French.).

We have to define
messages_en.properties for english
messages_es.properties for spanish
messages_fr.properties for french in the bundle folder of our application.

If you want to have different message resource files for English in the U.K. and English in the USA, you have to add the country code (en_GB, en_US).

messages _en_GB.properties
messages _en_US.properties

In our application, the default locale is English and we support Spanish and French.

Rename the message.properties we create in the previous section by messages_en.properties.

The property file messages_es.properties look like this:

select_language=Select Language
user_details_form=Usuario Detalla Forma
user_details=Usuario Detalla
name=Nombre
enter_name=Por favor, introduzca su nombre y apellidos
enter_name_validlength=Por favor, introduzca más de 3 caracteres para el nombre de
age=Edad
enter_age=Por favor, introduzca su edad
enter_correctage=Por favor, entrar en la edad correcta
email=Correo
enter_email=Por favor, introduzca su email
dob=Fecha de Nacimiento
enter_dob=Por favor, introduzca su fecha de nacimiento
enter_dobpattern=Por favor, introduzca la fecha en MM / DD / AAAA
submit=Enviar

The property file messages_fr.properties look like this:

select_language=Select Language
user_details_form=Forme de Détails d'Utilisateur
user_details=Détails d'Utilisateur
name=Nom
enter_name=S'il vous plaît entrer votre nom
enter_name_validlength=S'il vous plaît entrer plus de 3 caractères pour le nom
age=Âge
enter_age=S'il vous plaît entrer votre âge
enter_correctage=S'il vous plaît entrez âge correct
email=Email
enter_email=S'il vous plaît entrer votre e-mail
dob=Date de Naissance
enter_dob=S'il vous plaît entrer votre date de naissance
enter_dobpattern=S'il vous plaît entrer la date JJ / MM / AAAA
submit=Envoyer

Translation to spanish and french is done using google translator.

Configure locales

Now we have to tell JSF application which language it should support. We can specify the supported locales with the <local-config> element in the Faces configuration file, inside the <application> element.

<application>
        <resource-bundle>
                  <base-name>bundle.messages</base-name>
                   <var>msg</var>
         </resource-bundle>
         <locale-config>
                   <default-locale>en</default-locale>
                   <supported-locale>es</supported-locale>
                   <supported-locale>fr</supported-locale>
          </locale-config>
</application>

The element <default-locale> specifies the the default locale which is used if the current locale is not found. With the <supported-locale> element we define the locales that are supported by our web application. The <resource-bundle> tells the application where the properties files are located.The <default-locale> is automatically included in the list of <supported-locale>,so you don't need to declare it twice.

There are various ways to change the default language of JSF web application,

First Method:

When a browser connects to web application, it usually includes an Accept-Language value in the HTTP header. The value of the header may contain more than one language based on how the browser is configured.In internet explorer ,Tools->Internet Options,Click Language button in general Tab and specify your preferred locales.

\

                                               
In Mozilla,Tools->Options Click on Choose button corresponding to Language in Content tab

 
                                                                

                                               
If you specify more than one language the first one in the list will have the highest preference. Here French has highest preference.

If the browser claims to support the locale it(Italian), then JSF would make en(English) the current locale (for the browser session). That's because the application does not claim to support it(Italian). If the browser claimed to support the locale fr (French), then the locale for the browser session would be French(as the browser requested), because it's a supported locale.

Now, run your application:

Your page will be rendered in french, as shown:

                                                                                 

Second Method :

Another method is to define the locale attribute inside the f:view Tag . This can be done as hard coded string or as locale attribute of an bean.

For eg:
<f:view locale="es">

Set <f:view locale="es"> in UserDetailsForm.jsp and userDetailsSubmitted.jsp pages.Save your pages and run the application. Your page will be displayed in Spanish.

Since the 'locale' attribute in f:view tag supports EL, this approach will give more control to the application on internationalization. In the first method, user has to change their browser settings every time they wanted to use a website in a different language. So we will modify our application to allow the user to select the locale of their choice.

Step 1 : Create new jsp page,language.jsp (listed below).
Step 2 : Create a backing bean LanguageDetails.java (listed below).
Step 3 : Declare LanguageDetails Bean in faces-config.xml
Step 4 : Edit JSP Page UserDetailsForm.jsp and userDetailsSubmitted.jsp to add local attribute in f:view Tag  <f:view locale="#{languageDetails.locale}">
             Note:  UserDetailsForm.jsp : It's a simple web page which has 4 input text boxes and             a command button as listed here. UserDetailsSubmitted.jsp will display the details entered in the UserDetailsForm.jsp page. You can find the userDetailsSubmitted.jsp  here.
Step 5: Define Page Navigation.

See the steps in detail below:

Create new jsp page,language.jsp.
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="f" uri="http://java.sun.com/jsf/core"%>
<%@ taglib prefix="h" uri="http://java.sun.com/jsf/html"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Language Selection</title>
</head>
<body>
<f:view>
     <h:form>
          <h:panelGrid columns="2">
                <h:outputText value="Select Language"></h:outputText>
                <h:selectOneMenu id="dropdown" value="#{languageDetails.locale}">
                      <f:selectItem itemValue="en" itemLabel="English" />
                      <f:selectItem itemValue="es" itemLabel="Spanish" />
                      <f:selectItem itemValue="fr" itemLabel="French" />
                </h:selectOneMenu>
          </h:panelGrid>
          <p><h:commandButton id="change" value="Change Language"
           action="#{languageDetails.changeLanguage}" /></p>
      </h:form>
</f:view>
</body>
</html>


At runtime, page will be rendered like this:

                                                           
Create a backing bean LanguageDetails.java in the com.user.details package of the source folder.The class will have one attribute (locale) and getter and setter for that attribute. The bean simply captures the value selected from the dropdown after the user clicks the submit button.

package com.user.details;

public class LanguageDetails {

  private String locale;

  public void setLocale(String locale) {
    this.locale = locale;
  }

  public String getLocale() {
    return locale;
  }

  public String changeLanguage() {
    return "changed";
  }

}


Declare LanguageDetails Bean in faces-config.xml

You can see in Lesson 1 how to declare a bean in faces-config.xml. The scope of the languageDetails bean should be set as "session" so that the language selected can be used for the entire user session

<managed-bean>
       <managed-bean-name>languageDetails</managed-bean-name>
       <managed-bean-class>com.user.details.LanguageDetails</managed-bean-class>
       <managed-bean-scope>session</managed-bean-scope>
</managed-bean>

Defining Page Navigation

Define a navigation rule that says from the view language.jsp go to the view UserDetailsForm.jsp, if the outcome is "changed".

<navigation-rule>
       <display-name>pages/language</display-name>
       <from-view-id>/pages/language.jsp</from-view-id>
       <navigation-case>
             <from-outcome>changed</from-outcome>
             <to-view-id>/pages/UserDetailsForm.jsp</to-view-id>
       </navigation-case>
</navigation-rule>

Edit JSP Page

Add locale attribute in f:view Tag in UserDetailsForm.jsp and userDetailsSubmitted.jsp discussed in previous sections.

<f:view locale="#{languageDetails.locale}">

Edit index.jsp page

Here we are editing the entry point of the application to language.jsf
<html>
    <body>
         <jsp:forward page="/pages/language.jsf"></jsp:forward>
    </body>
</html>

Run your application

To run your web application, right click on BasicJSFProject, click- >run as -> run on server.
Select the server type ,Apache Tomacat v6.0 Server.Click Fininsh.

Open a web browser and type the url : http://localhost:8080/BasicJSFProject/

<< Previous       Next  >>

See More Topics:

How page navigation works in JSF?
How to use resource bundle in JSF?
How event handling works in JSF?
JSF Request Processing Life Cycle with example.