Show List

Internationalization (i18n)

Internationalization (i18n) is the process of designing a web application that can be adapted to different languages and regions. Spring MVC provides support for i18n through the LocaleResolver and MessageSource interfaces.

LocaleResolver is used to resolve the locale of the current request. There are several implementations provided by Spring MVC, including AcceptHeaderLocaleResolver and SessionLocaleResolver. The AcceptHeaderLocaleResolver uses the Accept-Language header of the request to determine the locale, while the SessionLocaleResolver uses the Locale attribute stored in the session.

For example, to configure the SessionLocaleResolver in your Spring MVC configuration:

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

  @Bean
  public LocaleResolver localeResolver() {
    SessionLocaleResolver localeResolver = new SessionLocaleResolver();
    localeResolver.setDefaultLocale(Locale.ENGLISH);
    return localeResolver;
  }

  @Bean
  public LocaleChangeInterceptor localeChangeInterceptor() {
    LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor();
    localeChangeInterceptor.setParamName("lang");
    return localeChangeInterceptor;
  }

  @Override
  public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(localeChangeInterceptor());
  }
}

MessageSource is used to resolve messages for the current locale. You can define messages in properties files, one for each locale, and place them in the classpath. The file name should follow the pattern messages_[locale].properties, where [locale] is the locale code, such as en or fr.

For example, to define messages in the messages_en.properties file:

welcome=Welcome to Spring MVC
message=This is a message
To access the messages in your controller or view, you can use the messageSource bean in your code:
@Autowired
private MessageSource messageSource;

...

String message = messageSource.getMessage("message", null, locale);
With these configurations, you can easily internationalize your Spring MVC application and provide support for multiple languages and regions.

    Leave a Comment


  • captcha text