1、编写LocaleResolver实现类
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
/**
* Author: liubenqiang
* Date: 2019/9/9
*
* 自定义解析器,解析http请求中的language信息
*/
public class DataVizLocalResolver extends AcceptHeaderLocaleResolver implements WebMvcConfigurer {
List<Locale> LOCALES = Arrays.asList(
new Locale("en"),
new Locale("zh"));
@Override
public Locale resolveLocale(HttpServletRequest request) {
String headerLang = request.getHeader("Accept-Language");
return headerLang == null || headerLang.isEmpty()
? Locale.CHINESE
: Locale.lookup(Locale.LanguageRange.parse(headerLang), LOCALES);
}
}
2、配置LocalResovler 的JavaBean
@Bean
public LocaleResolver localeResolver(){
return new DataVizLocalResolver();
}
3、新建资源文件
resource/i18n目录下,新建文件:
4、Spring配置国际化资源文件路径:
5、编写工具类根据当前语言环境获取Local Message
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Component;
/**
* Author: liubenqiang
* Date: 2019/9/9
*
* 国际化工具类,用于获取code对应的值
* */
@Component
public class MessageUtils {
@Autowired
private MessageSource messageSource;
public String getLocale(String msgCode) {
try {
return messageSource.getMessage(msgCode, null, LocaleContextHolder.getLocale());
} catch (Exception e) {
return msgCode;
}
}
}
6、测试
Http请求头,添加Accept-Language节点即可