Spring Boot 入门 - 基础篇(7)- 国际化

阅读更多
Spring Boot默认支持国际化配置,只需要添加配置文件即可。

(1)配置文件
放在/src/main/resources/文件夹下即可
  • messages.properties 默认
  • messages_en.properties(英文)
  • messages_zh.properties(中文)
  • messages_ja.properties(日文)

(2)默认配置
引用
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.


修改spring.messages.basename的配置:
引用
spring.messages.basename=i18n/messages_common,i18n/messages_api,i18n/messages_admin


以下文件将都会被加载
  • /src/main/resources/i18n/messages_common.properties
  • /src/main/resources/i18n/messages_api.properties
  • /src/main/resources/i18n/messages_admin.properties

(3)页面显示(Thymeleaf)
/src/main/resources/hello.html



(4)代码中使用
@Autowired
private MessageSource messageSource;

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


a- 获取request的Locale

Controller参数注入
@RequestMapping("/sample")
public String sample(Model model, Locale locale) {
    String message = messageSource.getMessage("search.condition", null, locale);
    log.info(message);
    return "sample";
}


代码获取
Locale locale1 = LocaleContextHolder.getLocale(); // 当前request
Locale locale2 = RequestContextUtils.getLocale(request); // 指定request


b- 通用的使用
@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)设置验证信息Validator

Hibernate Validator 和 JSR 303 validation API的提示信息,默认是ValidationMessages.properties。亦可以统一到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)设置语言

默认根据浏览器的语言设置来决定显示语言AcceptHeaderLocaleResolver。一般应用多采用会话级别的语言设置SessionLocaleResolver。
@Bean
public LocaleResolver localeResolver() {
    SessionLocaleResolver sessionLocaleResolver = new SessionLocaleResolver();
    sessionLocaleResolver.setDefaultLocale(Locale.CHINA);
    return sessionLocaleResolver;
}


(7)切换语言

a- 通过Interceptor

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


URL中通过参数lang就可以切换到不同语言。比如:http://localhost:8080/hello.html?lang=zh

b- 代码内设置语言
Locale locale = Locale.CHINA;
LocaleContextHolder.setLocale(locale);
request.getSession().setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME, locale);

你可能感兴趣的:(Spring Boot 入门 - 基础篇(7)- 国际化)