1.配置i18n(国际化)文件
建立login和login_en_US时会自动生成Bundle
配置默认值,英文,中文
2.页面设置值
这里用了thymeleaf模板,前面的文章有提到用法
<img class="mb-4" th:src="@{/img/bootstrap-solid.svg}" alt="" width="72" height="72">
<h1 class="h3 mb-3 font-weight-normal" th:text="#{login.tip}" >Please sign in</h1>
<input type="text" class="form-control" th:placeholder="#{login.username}" required="" autofocus="">
<input type="password" class="form-control" th:placeholder="#{login.password}" required="" >
<div class="checkbox mb-3">
<label>
<input type="checkbox" value="remember-me" >[[#{login.remenber}]]
测试一下值是否显示
两个超链接标签点击传值
<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>
3.编写自定义的LocaleResolver组件
public class MyLocalResolver implements LocaleResolver {
@Override
public Locale resolveLocale(HttpServletRequest httpServletRequest) {
//获取请求中的语言参数
String language = httpServletRequest.getParameter("l");
//如果没有返回值就用默认的
Locale locale = Locale.getDefault();
if (!StringUtils.isEmpty(language)){
//zh_CN or en_US
String[] split = language.split("_");
//国家,地区
locale = new Locale(split[0],split[1]);
}
return locale;
}
@Override
public void setLocale(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) {
}
}
将组件配置到spring容器
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
@Bean
public LocaleResolver localeResolver(){
return new MyLocalResolver();
}
}
测试
4.注意点
一定要把所有的编码都改为utf-8格式,否则可能会出现乱码