JSTL Resource Bundle for Internationalization and Localization

Yudong Li picture Yudong Li · Sep 18, 2012 · Viewed 25.6k times · Source

We have an application that using the basic JSP/servlet that all text currently in English is hard coded in the JSP pages. We are considering about internationalizations of our app, so we need some sort of ways to extract the text out into properties file.

Here is what I have done so far:
1) Create a file called XXXXX-messages_en.properties, add the key/value pair into the properties file, e.g. AAAAA = Hello World

2) Load JSTL relevant taglibs into the JSP page

<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>

3) Replace the previous text with

<fmt:message key="AAAAA" bundle="${XXXXX}"/>

4) Add setBundle tag into the JSP page:

<fmt:setBundle basename="XXXXX-messages" var="XXXXX"/>

And restart the server, everything is correctly displayed.

However, my question regarding the usage of JSTL internationalization library is:

QUESTION 1) It appears that I have to add <fmt:setBundle> tag into each of singe JSP pages, which is a bit ugly and if something needs to change in the future (name change?) this will make life more difficult.

I have think about maybe I can create a separate page and put this <fmt:setBundle> in it, and then include this page using <jsp:include>. Or I can inject this via a servlet filter? I would say I am not quite happy with either options.

Is there any recommended way to do this?

QUESTION 2) How to specify a default language if there is no match properties file there? I have tested in my case, if I put <fmt:setLocale> into the JSP page with a French language, the page can still loaded correctly. Does that mean the English version is always the default or is it simply because my operating system/browser is English?

What will happen if a Chinese/Japanese user open my page and I have both English and French properties file there?

Answer

Yudong Li picture Yudong Li · Sep 18, 2012

OK, I found the way to solve my own question 1. Basically what I need to do is put that into web.xml:

<context-param>
    <param-name>javax.servlet.jsp.jstl.fmt.localizationContext</param-name>
    <param-value>XXXXX-messages</param-value>
</context-param>

By doing this, I can save the tag of setBundle in each jsp pages.