Saturday, 22 November 2014

Adding internationalization support to spring mvc with thymeleaf

For basic Thymeleaf configuration check Spring MVC with Thymeleaf

Thymeleaf uses Standerd messange resolver unless specified which on to use. We can also use Spring internationalization support which will be supported by default by Thymeleaf.

Steps:

  1. Add messages_en file to src/main/resources/

  2. Add spring beans those will support internationalization.
    <?xml version="1.0" encoding="UTF-8"?>
    <bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
    <property name="basename" value="classpath:messages" />
    <property name="defaultEncoding" value="UTF-8" />
    </bean>

    <bean id="localeChangeInterceptor" class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
    <property name="paramName" value="lang" />
    </bean>

    <bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver">
    <property name="defaultLocale" value="en" />
    </bean>

    <bean id="handlerMapping" class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
    <property name="interceptors">
    <ref bean="localeChangeInterceptor" />
    </property>
    </bean>


  3. LocaleChangeInterceptor is handler mapping that need to supports the multiple languages. The "paramName" is the parameter value that’s used to set the locale.

  4. Use ?lang=fr to change language to French from default English.


Source: Source Code

No comments:

Post a Comment