一、编写配置文件
在resoures下创建两个以上结构相同的配置文件(例如login.properties与login_zh_CN.properties)就会自动生成ResourcesBundle。
点击+号,添加相应的属性与对应的值即可。
再在application.properties或application.yml里配置spring.messages.basename=i18n.login
(resources下的文件夹名和里面的文件名)
二、编写前端页面
<form class="form-signin">
<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.remember}]]
</label>
</div>
<button class="btn btn-lg btn-primary btn-block" type="submit">[[#{login.btn}]]</button>
<p class="mt-5 mb-3 text-muted">© 2019-2020</p>
<a class="btn btn-sm" th:href="@{/index(l='zh_CN')}">中文</a>
<a class="btn btn-sm" th:href="@{/index(l='en_US')}">English</a>
</form>
thymeleaf语法:th:text="#{}"
#可以解析国际化配置文件的属性,在半闭合标签情况下用[[]]里面写#{}解析。
三、后端代码编写
1.编写controller类
@Controller
public class HelloController {
//RequestMapping必须与前端点击语言时访问的路径一致
@RequestMapping("/index")
public String hello(){
return "index";
}
}
2.创建一个类实现LocaleResolver接口,并重写方法
public class MyLocaleResolver implements LocaleResolver {
@Override
public Locale resolveLocale(HttpServletRequest request) {
//获取请求中的语言参数
String langu = request.getParameter("l");
Locale locale=Locale.getDefault();
//判断请求链接是否有语言参数
if (!StringUtils.isEmpty(langu)){
//参数形如:zh_CN,将参数进行切割
String[] s = langu.split("_");
//设置国家,地区
locale=new Locale(s[0],s[1]);
}
return locale;
}
}
3.向Spring容器中添加组件
@SpringBootApplication
public class SpringbootApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootApplication.class, args);
}
@Bean
public LocaleResolver localeResolver(){
return new MyLocaleResolver();
}
}