1、在resources下建立i18n文件夹,并在文件夹下建立login.properties文件,之后建立login_en_US.properties文件,之后识别这是一个国家化的文件,会出现“Resource Bundle ‘login’”,之后右键这个标记,new-add一个
操作如图片:
输入语言_地区(如:en_US)就可以新建一个另一个语言的文件。
2、设置默认字符设置(防止乱码):
file-setting-file encoding 全部设置成为utf-8,并进行勾选。
3、随意打开一个文件,点击Resource Bundle,对值进行设置
4、于页面引用值(举个例子)
<h1 class="h3 mb-3 font-weight-normal" th:text="#{login.tip}">Please sign in</h1>
5、在application.yml进行设置
spring:
messages:
basename: i18n.login
6、写一个自己的MyLocaleResolver继承LocaleResolver自己进行相关国际化配置.
public class MyLocaleResolver implements LocaleResolver {
@Override
public Locale resolveLocale(HttpServletRequest httpServletRequest) {
String l=httpServletRequest.getParameter("l");
Locale locale=Locale.getDefault();
if(!StringUtils.isEmpty(l)){
String[] split=l.split("_");
locale= new Locale(split[0],split[1]);
}
return locale;
}
@Override
public void setLocale(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) {
}
}
7、加入容器中,使其生效
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("login");
//视图解析器
registry.addViewController("/index.html").setViewName("login");
}
@Bean
public LocaleResolver localeResolver(){
return new MyLocaleResolver();
}
}
8、点击相关,之后切换,于页面中进行设置
<a class="btn btn-sm" th:href="@{/index.html(l='zh_CN')}">中文</a>
<a class="btn btn-sm" th:href="@{/index.html(l='en_US')}">English</a>
(注意这里的/index.html经过之前的配置类进行了相关的视图解析了!)