Getting Started with Spring Boot - Basics (7) - Internationalization

Spring Boot supports internationalization configuration by default, you only need to add configuration files.

(1) The configuration file
can be placed in the /src/main/resources/ folder
  • messages.properties default
  • messages_en.properties (English)
  • messages_zh.properties (Chinese)
  • messages_ja.properties (Japanese)

(2) Default configuration
quote
spring.messages.always-use-message-format=false # Set whether to always apply the MessageFormat rules, parsing even messages without arguments.
spring.messages.basename=messages # Comma-separated list of basenames, each following the ResourceBundle convention.
spring.messages.cache-seconds=-1 # Loaded resource bundle files cache expiration, in seconds. When set to -1, bundles are cached forever.
spring.messages.encoding=UTF-8 # Message bundles encoding.
spring.messages.fallback-to-system-locale=true # Set whether to fall back to the system Locale if no files for a specific Locale have been found.


Modify the configuration of spring.messages.basename:
quote
spring.messages.basename=i18n/messages_common,i18n/messages_api,i18n/messages_admin


The following files will all be loaded
  • /src/main/resources/i18n/messages_common.properties
  • /src/main/resources/i18n/messages_api.properties
  • /src/main/resources/i18n/messages_admin.properties

(3) Page display (Thymeleaf)
/src/main/resources/hello.html
<h1 th:text="#{search.condition}"></h1>


(4) used in the code
@Autowired
private MessageSource messageSource;

String msg = messageSource.getMessage("search.condition", null, locale);


a- Get the Locale

Controller parameter injection of the request
@RequestMapping("/sample")
public String sample(Model model, Locale locale) {
    String message = messageSource.getMessage("search.condition", null, locale);
    log.info(message);
    return "sample";
}


code acquisition
Locale locale1 = LocaleContextHolder.getLocale (); // 当前 request
Locale locale2 = RequestContextUtils.getLocale(request); // 指定request


b- Generic use
@Component
public class MessageManager {

    private static MessageSource messageSource;

    public static String getMsg(String key) {
        Locale locale = LocaleContextHolder.getLocale ();
        return messageSource.getMessage(key, null, locale);
    }

    public static String getMsg(String key, String... arg) {
        Locale locale = LocaleContextHolder.getLocale ();
        Object[] args = new Object[arg.length];
        for (int i = 0; i < arg.length; i++) {
            args[i] = arg[i];
        }
        return messageSource.getMessage(key, args, locale);
    }

    @Autowired(required = true)
    public void setMessageSource(MessageSource messageSource) {
        MessageManager. messageSource = messageSource;
    }

}


String msg = MessageManager.getMsg("search.condition");


(5) Set

the prompt information of the validation information Validator Hibernate Validator and JSR 303 validation API, the default is ValidationMessages.properties. It can also be unified into messages.properties.
@Configuration
public class MessageConfig extends WebMvcConfigurerAdapter {
    @Autowired
    private MessageSource messageSource;

    @Bean
    public LocalValidatorFactoryBean validator() {
        LocalValidatorFactoryBean localValidatorFactoryBean = new LocalValidatorFactoryBean();
        localValidatorFactoryBean.setValidationMessageSource(messageSource);
        return localValidatorFactoryBean;
    }

    @Override
    public Validator getValidator() {
        return validator();
    }
}


(6) Setting the language

By default, the display language AcceptHeaderLocaleResolver is determined according to the language settings of the browser. Generally, the SessionLocaleResolver is set in the language of the session level for general applications.
@Bean
public LocaleResolver localeResolver() {
    SessionLocaleResolver sessionLocaleResolver = new SessionLocaleResolver();
    sessionLocaleResolver.setDefaultLocale(Locale.CHINA);
    return sessionLocaleResolver;
}


(7) Switch language

a- through Interceptor

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


You can switch to different languages ​​through the parameter lang in the URL. For example: http://localhost:8080/hello.html?lang=zh

b- Set the language in the code
Local local = Local.CHINA;
LocaleContextHolder.setLocale(locale);
request.getSession().setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME, locale);

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326844031&siteId=291194637