-
引言
今天在开发过程中,遇到国外客户,要求项目一些返回msg中,不能再有中文,于是便有了国际化需求。
-
How to do
1.在项目resources下创建i18n文件夹以及messages.properties文件
messages.properties 国际化主文件
phoneErr.msg=The phone number err
messages_en.properties 英文配置文件
phoneErr.msg=The phone number err
messages_zh.properties 中文配置文件
phoneErr.msg=手机号错误
这三个文件缺一不可
2.在项目中创建MyLocaleResolver.java
@Configuration
public class MyLocaleResolver {@Beanpublic LocaleResolver localeResolver() {log.info("LocaleResolver loading...");SessionLocaleResolver slr = new SessionLocaleResolver();slr.setDefaultLocale(Locale.SIMPLIFIED_CHINESE); // 设置默认语言
// slr.setDefaultLocale(Locale.US); // 设置默认语言return slr;}@Beanpublic MessageSource messageSource() {ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();messageSource.setBasename("classpath:i18n/messages");messageSource.setDefaultEncoding("UTF-8");return messageSource;}}
3.切换中英文,采用自定义spring拦截器方式
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {@Overridepublic void addInterceptors(InterceptorRegistry registry) {registry.addInterceptor(new MyInterceptor());}class MyInterceptor implements HandlerInterceptor {@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {String header = request.getHeader("Accept-Language");if (StrUtil.isBlank(header)) {return true;} else if ("zh".equals(header)) {LocaleContextHolder.setLocale(Locale.SIMPLIFIED_CHINESE);} else if ("en".equals(header)) {LocaleContextHolder.setLocale(Locale.US);}return true;}}
}
前端可在接口请求头中添加 Accept-Language=en/zh 用于区别中英
4.应用
@Autowiredprivate MessageSource messageSource;@RequestMapping("/test")public String getMessage() {
// 根据code从环境中自动获取对应国际化内容return messageSource.getMessage("phoneErr.msg", null, LocaleContextHolder.getLocale());}
5.测试