1.创建配置文件
①在resources创建国际化配置文件包 i18n
②创建一个Resource Bundle类型,名字为login
③右击Buddle
④添加后点击OK
⑤添加配置文件属性
2.前端读取国际化配置文件属性和携带语言信息
3.让springboot使用我们自定义的LocaleResolver 区域信息解析器
①创建一个MyLocalResolver
/**
* 可以在连接上携带区域信息
*/
public class MyLocalResolver implements LocaleResolver {
@Override
public Locale resolveLocale(HttpServletRequest request) {
String l = request.getParameter("l"); //取前端访问路径中携带的信息
Locale locale = Locale.getDefault(); //没有携带的时候用默认值
if(!StringUtils.isEmpty(l)){
String[] split = l.split("_");
locale = new Locale(split[0],split[1]); //将en_US拆分成,en和US,有参构造到区域信息中
}
return locale;
}
@Override
public void setLocale(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) {
}
}
②把MyLocalResolver在MyMvcConfig中注入容器
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
@Bean
public WebMvcConfigurer webMvcConfigurer(){
WebMvcConfigurer webMvcConfigurer = new WebMvcConfigurer() {
@Override
//定义访问路径
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("login");
registry.addViewController("/index.html").setViewName("login");
}
};
return webMvcConfigurer;
}
@Bean //将MyLocalResolver注册到容器中,让系统使用我们定义的LocalResolver
public LocaleResolver localeResolver(){
return new MyLocalResolver();
}
}
4.application.properties 定位国际化配置文件的位置
spring.messages.basename=i18n.login