January 21, 2010

Internationalization for client side scripting in JSP applications

If you are using JSP in a web application which uses i18n, you probably came across the problem of having to internationalize your client-side validation error messages as well, such as JavaScript error messages.

The problem is that i18n settings are usually defined at the application level, such as the web deployment descriptor of your Tomcat server or in your Java classes, and there's no straight forward way of applying the same settings to your client side code.

Here is a solution (maybe not the best one) but nonetheless, which will let you do client-side internationalized messages with relative ease for any JSP/Servlet based application:

Step 1: Create the files

Create 2 or more js files for each language you are using and place them in your app directory structure

  • webapproot/scripts/validation.strings.js //english version
  • webapproot/scripts/validation.strings.ro.js //romanian version

Step 2: Add the localized strings to each file

validation.strings.js: validation.strings.ro.js:

Step 3: Include the localized scripts based on your locale

Add the following code to the jsp page on which you will be using internationalized client-side messages. In our case we only have two languages, and the default is english (validation.strings.js), but you can modify the code below to use any number of them.


<c:choose>
   <c:when test="${sessionScope['javax.servlet.jsp.jstl.fmt.locale.session'] eq 'ro'}">
      <script src="<%= request.getContextPath()%>/scripts/validation.strings.ro.js" type="text/javascript"></script>
   </c:when>
   <c:otherwise>
      <script src="<%= request.getContextPath()%>/scripts/validation.strings.js" type="text/javascript"></script>        
   </c:otherwise>    
</c:choose>

To find out more about setting the locale in a Java Web Application using Tomcat read this post

Step 4: Call the JavaScript code

Finally you can now reference an internationalized JavaScript message from your JSP page as in the example below:

Step 5: Done

If you did everything correctly and your locale is set to 'ro', you should get an alert saying 'Acest camp nu a fost completat'