最近公司做了个购票项目,业务扩展到了泰国,所以网站要支持泰语、英语和中文,因此有了下文。
配置文件准备:
根目录或者i18n目录放置需要的翻译,每个配置文件对应不同的翻译
messages是默认展示的翻译 我这里为英文
messages_th_TH:
email_format_error=รูปแบบอีเมลไม่ถูกต้อง
messages_en_US:
email_format_error=incorrect email format
messages_zh_CN:
email_format_error=邮箱格式错误
项目配置
## 配置消息资源
@Bean
public ResourceBundleMessageSource getBundleMessageSource(){
ResourceBundleMessageSource r = new ResourceBundleMessageSource();
r.setBasenames("messages");
r.setDefaultEncoding("UTF-8");
return r;
}
@Component
public class I18nComponent {
private static final java.util.List<Locale> DEFAULT_ACCEPT_LOCALES = Arrays.asList(Locale.US, Locale.SIMPLIFIED_CHINESE, new Locale("th", "TH"));
/**
* 请求头信息,通过此解析locale
* 前台lan 参数为:zh_CN,th_TH,en_US 和配置文件后缀对应
*/
private static final String HTTP_ACCEPT_LANGUAGE = "lan";
@Autowired
private ResourceBundleMessageSource bundleMessageSource;
public Locale getLocale() {
// 从请求头获取语言参数
ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
if (servletRequestAttributes == null) {
return Locale.getDefault();
}
HttpServletRequest httpServletRequest = servletRequestAttributes.getRequest();
String locale = httpServletRequest.getHeader(HTTP_ACCEPT_LANGUAGE);
if (StringUtils.isEmpty(locale)) {
return Locale.getDefault();
}
return Locale.lookup(Locale.LanguageRange.parse(locale), DEFAULT_ACCEPT_LOCALES);
}
// 获取翻译消息
public String getLocaleMessage(Object errorEnum) {
Locale locale = getLocale();
String message = bundleMessageSource.getMessage(errorEnum.toString().toLowerCase(), null, locale);
return message;
}
public String getLocaleMessage(String propertyKey) {
Locale locale = getLocale();
String message = bundleMessageSource.getMessage(propertyKey, null, locale);
return message;
}
public String getLocaleMessageWithPlaceHolder(String propertyKey, Object... params) {
Locale locale = getLocale();
String message = bundleMessageSource.getMessage(propertyKey, params, locale);
return message;
}
}