May 22, 2009

Spring Localization Example

« Spring MVC - Example | Main | JUNG - Graphen modellieren mit Java »

The Spring Framework supports and enhance the standard localization java mechanism with property files in order to provide an easy of use of resource bundles.

A problem of the standard mechanism is the difficulty of reloading resource bundles. The ReloadableResourceBundleMessageSource class reloads and caches the configured resource bundles. Anymore it enables to setting the encoding. Usually the enconding of java resource bundles is fixed (ISO-8859-1). Spring ignores this fixation and enables the setting of other enconding types. The bean property basenames of the ResouceBundleMessageSource bean contains a basename list. Basenames define the prefixes of the used resource bundles files. For the basename "messages" the following filenames are possible: messages.properties, messages_de_DE.properties, message_en_GB.properties and so on. The resource bundle files should be available at the /WEB-INF/classes directory.

<!-- declare the MessageSource bean -->
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
  <property name="cacheSeconds" value="3"/>
  <property name="defaultEncoding" value="UTF-8"/>
  <property name="basenames">
    <list>
      <value>classpath:messages</value>
    </list>
  </property>
</bean>

After that you have to define a LocaleChangeInterceptor and a LocaleResolver. The LocaleChangeInterceptor evaluate the locale url parameter (/path?locale=en_US or /path?locale=de_DE). The interpreted locale will be saved as a cookie or as a session attribute. Resolvers as "SessionLocaleResolver", "CookieLocaleResolver", "AcceptHeaderLocaleResolver" and so on resolves the choiced locale. The "LocaleChangeInterceptor" still have to be added at the UrlHandlerMapping.

<!-- declare the interceptor -->
<bean id="localeChangeInterceptor" class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"/>

<!-- declare the resolver -->
<bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver"/>

<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
  <property name="urlMap">
    <map>...</map>
  </property>
  <property name="interceptors">
    <list>
      <!-- adding locale interceptor bean -->
      <ref local="localeChangeInterceptor"/>
    </list>
  </property>
</bean>

Regards
Rafael Sobek

Technorati Tags:

Posted by rafael.sobek at 4:04 PM in Spring

 

 
test