My linux world » Java Spring – Locale

Java Spring - Locale


Contents

Prerequistes

Please read : Java spring – quickstart

Configuration

WebMvcConfig.java

In WebMvcConfig.java, add the following beans :

  @Bean
  public MessageSource messageSource() {
    ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
    messageSource.setBasename("classpath:messages");
    messageSource.setDefaultEncoding("UTF-8");
    return messageSource;
  }
  @Bean
  public LocaleResolver localeResolver(){
    CookieLocaleResolver resolver = new CookieLocaleResolver();
    resolver.setDefaultLocale(new Locale("en"));  
    return resolver;
  }

Still WebMvcConfig.java, register interceptor:

  @Override
  public void addInterceptors(InterceptorRegistry registry) {
    LocaleChangeInterceptor interceptor = new LocaleChangeInterceptor();
    interceptor.setParamName("lang");
    registry.addInterceptor(interceptor);
  }

Resources

Create the following file src/main/resources/messages_en.properties :

label.message=message from message_en.properties

Create the following file src/main/resources/messages_fr.properties :

label.message=message from message_fr.properties

JSP

In your jsp file, you can change language like this :

<a href="?lang=en" id="lang-en">en</a> 
| 
<a href="?lang=fr" id="lang-fr">fr</a>
</span>

and print message like this :

<%@ taglib uri="http://www.springframework.org/tags" prefix="spring"%>
 
<spring:message code="label.message"/>

Copyright © 2023 My linux world - by Marc RABAHI
Design by Marc RABAHI and encelades.

Fork me on GitHub