Sunday, 18 November 2012

Spring Internationalization Example (with Annotations)

Spring InternationalizationThis post describes how to implement message internationalization in Spring. The code example is available from GitHub in the Spring-MVC-Internationalization directory. It is based on the Spring MVC with annotations example.


We define two resource bundles (setA and setB) containing string translations for German, French and English. These are created in the src/main/resources maven directory.


We need to create:
  • a ResourceBundleMessageSource bean to load the string translations
  • a LocaleChangeInterceptor bean which will intercept requests and extract a parameter value (if available) to detect language changes
  • a SessionLocaleResolver bean to store the user's locale preference in the session
  • to register the LocaleChangeInterceptor in the interceptor registry
 We extend our web configuration:
@ComponentScan(basePackages = "com.jverstry")
public class WebConfig extends WebMvcConfigurerAdapter {


    public MessageSource messageSource() {
        ResourceBundleMessageSource result
            = new ResourceBundleMessageSource();

        String[] basenames = {


        return result;


    public LocaleChangeInterceptor localeChangeInterceptor() {

        LocaleChangeInterceptor result = new LocaleChangeInterceptor();

        return result;


    public LocaleResolver localeResolver() {

        SessionLocaleResolver result = new SessionLocaleResolver();

        return result;


    public void addInterceptors(InterceptorRegistry registry) {



We simply our controller a lot:
public class MyController {

    @RequestMapping(value = "/")
    public String home() {
        return "index";


JSP Page

We only keep the index.jsp page, where we add links to change the language of displayed messages:
<%@ page contentType="text/html;charset=UTF-8" %>
<%@ taglib prefix="c" uri="" %>
<%@ taglib uri="" prefix="spring" %>
<!doctype html>
<html lang="en">
  <title>Welcome To Spring MVC Internationalization !!!</title>
  <h1>Spring MVC Internationalization !!!</h1>
      <a href="<c:url value='?lang=en'/>">English</a>
      | <a href="<c:url value='?lang=fr'/>">French</a>
      | <a href="<c:url value='?lang=de'/>">German</a>

  <p>Greetings: <spring:message code="greetings" text="missing" /></p>
  <p>Text 2: <spring:message code="text2" text="missing" /></p>
  <p>Current: <c:out value="${pageContext.response.locale}" /></p>

Running The Example

Once compiled, the example can be run with mvn tomcat:run. Then, browse:


The main page will be displayed:

If you click on German, the German text is displayed:

More Spring related posts here.

1 comment:

  1. thank you for the tutorial
    i always wondering how to make web application supports multi languages,
    i thought it was hard, but after see your blog post i can achieve it easily using Spring
    once again thank you :)