登录页面中英文切换
<a class="btn btn-sm" th:href="@{/login.html(l='zh_CN')}">中文</a>
<a class="btn btn-sm" th:href="@{/login.html(l='en_US')}">English</a>
在resources下创建i18n的目录,再创建配置文件
编写配置文件
修改前端需要语言切换的内容
<form class="form-signin" action="dashboard.html">
<h1 class="h3 mb-3 font-weight-normal" th:text="#{login.tip}">Please sign in</h1>
<label class="sr-only" th:text="#{login.username}">Username</label>
<input type="text" class="form-control" placeholder="Username" th:placeholder="#{login.username}" required="" autofocus="">
<label class="sr-only" th:text="#{login.password}">Password</label>
<input type="password" class="form-control" placeholder="Password" th:placeholder="#{login.password}" required="">
<div class="checkbox mb-3">
<label>
<input type="checkbox" value="remember-me" > [[#{login.remenber}]]
</label>
</div>
<button class="btn btn-lg btn-primary btn-block" type="submit" th:text="#{login.btn}">Sign in</button>
<p class="mt-5 mb-3 text-muted">@deyi</p>
<a class="btn btn-sm" th:href="@{/login.html(l='zh_CN')}">中文</a>
<a class="btn btn-sm" th:href="@{/login.html(l='en_US')}">English</a>
</form>
在application.properties配置文件中添加如下代码
#配置国际化文件的名称,把国际化配置文件加载进来
spring.messages.basename=i18n.login
创建自己的LocaleResolver,重写里面的resolveLocale方法
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[] s = l.split("_");
//Locale类中有对应的语言,注意不用双引号
System.out.println(s[0]);
System.out.println(s[1]);
locale = new Locale(s[0],s[1]);
}
return locale;
}
@Override
public void setLocale(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) {
}
}
要用@bean注解把MylocaleResolver 注入到容器中
源码中@ConditionalOnMissingBean的意思是容器中没有配置自己的区域信息解析器的时候就执行该方法,用它本身的区域信息解析器
@Bean
@ConditionalOnMissingBean
@ConditionalOnProperty(prefix = "spring.mvc", name = "locale")
public LocaleResolver localeResolver() {
if (this.mvcProperties.getLocaleResolver() == WebMvcProperties.LocaleResolver.FIXED) {
return new FixedLocaleResolver(this.mvcProperties.getLocale());
}
AcceptHeaderLocaleResolver localeResolver = new AcceptHeaderLocaleResolver();
localeResolver.setDefaultLocale(this.mvcProperties.getLocale());
return localeResolver;
}
在Mywebconfig里面,用@bean注解把MylocaleResolver 注入到容器中
@Bean
public LocaleResolver localeResolver(){
return new MylocaleResolver();
}
可以运行了,点击中英文注意url是否出现zh_CN或者en_US
如果出现乱码问题,请看这篇博客
springboot国际化乱码解决方法