Sunday, February 5, 2012

JSTL Practice: I18N (Internationalization) practice, Locale, Bundle and Message.

We sometimes want to display a message in several different language,
i.e., I18N,Internationalization,
we can achieve this with JSTL by the steps below:

Step 1: Prepare the resource of message bundle.

For easy management, we create a package 'test.jstl.i18n.resources' and create four '.resource' file as below:




i18n_test.resource default

actually you can put these files at any location, and use any sub name '.whatever',
because we do not use these files directly, they are just the resource file to generate the real bundle file.

Make sure to change their encoding to 'UTF-8', you can change their encoding as below:
Right click on file then click properties

Change Text file encoding to UTF-8 if it is not default

Step 2: Generate the message bundle from resource files

After the resource files prepared, we copy them to a tmp folder such like C:/tmp,
and use the native2ascii under jdk/bin to generate message bundle as below:

c:\Program Files\Java\jdk1.6.0_24\bin>native2ascii -encoding UTF-8 c:\tmp\i18n_test_en_US.resource c:\tmp\

c:\Program Files\Java\jdk1.6.0_24\bin>native2ascii -encoding UTF-8 c:\tmp\i18n_test_ja_JP.resource c:\tmp\

c:\Program Files\Java\jdk1.6.0_24\bin>native2ascii -encoding UTF-8 c:\tmp\i18n_test_fr_FR.resource c:\tmp\

c:\Program Files\Java\jdk1.6.0_24\bin>native2ascii -encoding UTF-8 c:\tmp\i18n_test.resource c:\tmp\

after the message bundle generated, we create a new package '' and put the bundles into the package.

Step 3. Use 'setBundle' tag to load bundle then use 'message' tag to display message

Assume we have a page as below:


<%@ page isErrorPage="true" language="java"
    contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!-- This is the uri for JSTL 1.2 -->
<%@taglib prefix="fmt" uri=""%>
<%@taglib prefix="c" uri=""%>
<!-- EL is required -->
<%@ page isELIgnored ="false" %>
<!-- This page practice the setBundle message tag -->
        <meta http-equiv="Content-Type" 
            content="text/html; charset=UTF-8"/>
        <title>practice three: I18N (Internationalization)</title>
        <script type="text/javascript" src="js/practice_three.js"></script>
        <!-- load bundle if it is null (without locale setting) -->
        <c:if test="${testBUndle == null}">
            <fmt:setBundle basename=""
                var="testBundle" scope="session"/>
        <!-- The language select menu, call javascript to change locale when changed -->
        <select id="langVal" onChange="i18n.changeLocale(this.value, '${currentLocale}');" selectedIndex="1">
            <!-- The first option display the current language -->
            <option value="${currentLocale}">${currentLanguage}</option>
            <option value="en_US">English</option>
            <option value="ja_JP">日本語</option>
            <option value="fr_FR">Français</option>
            <option value="de_DE">Deutsch</option>

        <!-- out put the message with respect to the key '' -->
        <fmt:message key=""

The result will be

There is no locale setting, it will use the default setting from your browser, in this case is en_US,

The setBundle tag will load bundle which file nam
is [basename+locale].properties,

If it can not find such a file, it will use the default bundle,
which named [basename].properties,

The message tag will display the value of the key in the bundle,
i.e., coffee,
which is the value of the key '' in bundle

The first option of select element is
based on the variabl currentLocale and currentLanguage in the session scope.
after you select a locale in the selectbox,
an Ajax request will post to another page to change locale.

Step 4: Use Ajax to post change locale request.

The Javascript file used to send change-locale request in the page before is as below:


if (!window.i18n)
    i18n = {};
i18n.changeLocale = function (locale, current) {
    var request;
    // do nothing if not changed
    if (locale == current)

    // get a request
    if (request = this.getXmlHttpRequest()) {
        // do post and bring locale value as param['lang']'POST', 'practice_three__internationalization_lang_page.jsp?lang='+locale);
    // refresh document after request success
    request.onreadystatechange = function() {
        if(request.readyState === 4 && request.status === 200)
            document.location.href = document.location.href;

//get the XmlHttpRequest object
i18n.getXmlHttpRequest = function () {
    if (window.XMLHttpRequest
        && (window.location.protocol !== 'file:' 
        || !window.ActiveXObject))
        return new XMLHttpRequest();
    try {
        return new ActiveXObject('Microsoft.XMLHTTP');
    } catch(e) {
        throw new Error('XMLHttpRequest not supported');

The function 'i18n.changeLocale' will check whether the locale is changed first, if it is changed,
post a request to page 'practice_three__internationalization_lang_page.jsp'
and bring the new locale value with param name 'lang'

After the request success, it will reload current page to display the message with new locale.

Step 5: Use 'setLocale' tag to change locale and use 'setBundle' to reload appropriate bundle

The page that receive the change locale request and change locale is as below


<%@ page isErrorPage="true" language="java"
    contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!-- This is the uri for JSTL 1.2 -->
<%@taglib prefix="fmt" uri=""%>
<%@taglib prefix="c" uri=""%>
<!-- EL is required -->
<%@ page isELIgnored ="false" %>
<!-- This page practice setLocale and setBundle tag -->
        <meta http-equiv="Content-Type" 
            content="text/html; charset=UTF-8"/>
        <title>practice three: I18N (Internationalization)</title>
        <!-- Set the locale by the value of parameter 'lang' -->
        <fmt:setLocale value="${param['lang']}" scope="session" />
        <!-- Should load bundle again with the new locale -->
        <fmt:setBundle basename=""
            var="testBundle" scope="session"/>
        <!-- set the value of currentLocale -->
        <c:set var="currentLocale" value="${param['lang']}" scope="session" />

        <!-- Set the value of currentLanguage -->
            <c:when test="${param['lang'] eq 'ja_JP'}">
                <c:set var="currentLanguage" value="日本語" scope="session" />
            <c:when test="${param['lang'] eq 'fr_FR'}">
                <c:set var="currentLanguage" value="Français" scope="session" />
            <c:when test="${param['lang'] eq 'de_DE'}">
                <c:set var="currentLanguage" value="Deutsch" scope="session" />
                <c:set var="currentLanguage" value="English" scope="session" />

It set the locale to the value of parameter 'lang' by setLocale tag,
then reload bundle to change to different bundle.

It also store two variable currentLocale and currentLanguage into session scope.

Finally we can display the 'coffee' in different language, note we do not have the bundle of locale de_DE,
it will display the message in default bundle (value is coffee default) when we select Deutsch:


You can download the full project at github

The files of this practice:


1 comment:

  1. Hello! If you ever need to internationalize a website, app or other software product, I suggest to have a look at like POEditor which is collaborative translation management platform aimed at automating and simplifying the workflow.