SpringBoot-页面国际化
项目构建
1. 创建SpringBoot项目
- 勾选WEB模块和Thymeleaf模块
- 设置properties编码问题
2. 导入静态资源
- 将准备好的静态页面导入到项目中
- 静态页面中引入Thymeleaf命名空间
即在<html>
标签中加入xmlns:th="http://www.thymeleaf.org"
<html lang="en" xmlns:th="http://www.thymeleaf.org">
3. 书写配置文件
-
在resources资源文件下新建一个i18n目录,用来存放国际化配置文件
-
建立login.properties文件,还有login_zh_CN.properties文件,以及login_en_US.properties文件;
-
login.properties文件,还有login_zh_CN.properties文件用来存放页面元素中文意思;
-
login_en_US.properties文件用来存放页面元素英文意思;
-
注意IDEA会自动识别了我们的操作,将文件夹进行了整合
-
通过使用Resource Bundle视图,来添加配置
在这个视图中点击“+”号就可以直接添加属性;如现在新建一个login.tip
-
依次添加其他内容
login.propertieslogin.btn=登录 login.password=密码 login.remember=记住我 login.tip=请登录 login.username=用户名
login_zh_CN.properties
login.btn=登录 login.password=密码 login.remember=记住我 login.tip=请登录 login.username=用户名
login_en_US.properties
login.btn=Sign in login.password=Password login.remember=Remember me login.tip=Please Sign in login.username=Username
-
在SpringBoot配置文件中添加如下配置
# 关闭thymeleaf模板缓存 spring.thymeleaf.cache=false # 绑定国际化配置文件 spring.messages.basename=i18n.login
4. 前端页面修改
在前端页面中获取国际化的值,通过Thymeleaf中获得message值的表达式:#{变量名}
此时,访问http://localhost:8080/
,前端默认识别中文
5. 书写配置类
- 修改前端页面的跳转路径
<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>
- 书写自己的配置类
- 实现localResolver接口,重写resolveLocale方法
public class MySolver implements LocaleResolver {
@Override
public Locale resolveLocale(HttpServletRequest httpServletRequest) {
String ln = httpServletRequest.getParameter("l");
// 获取默认的locale对象,若获得ln对象为空时,走默认的
Locale locale = Locale.getDefault();
// public Locale(String language, String country) {
// this(language, country, "");
// }
if(!StringUtils.isEmpty(ln)){
String[] s = ln.split("_");
// 参数一:语言类型 参数二:国家
locale =new Locale(s[0],s[1]);
}
return locale;
}
@Override
public void setLocale(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) {
}
}
- 在使用@Configuration注解的类中,注册咱们自己写的MySolver;
@Configuration
public class MyWebMvcConfig implements WebMvcConfigurer {
@Bean
public LocaleResolver localeResolver(){
return new MySolver();
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
// 添加拦截器
}
@Override
public void addViewControllers(ViewControllerRegistry registry) {
// 添加视图跳转路径
registry.addViewController("/index").setViewName("index");
}
}
6. 前端页面测试