前言
i18n(其来源是英文单词 internationalization的首末字符i和n,18为中间的字符数)是“国际化”的简称。根据需要可以切换到不同语言环境界面。
一、使用步骤
1.通过Idea开发工具构建
- New Project选择Spring Initializr来快速构建一个SpringBoot Web项目,本示例使用的JDK1.8和Maven。
- 选择依赖Thymeleaf和SpringWeb,点击下一步完成构建操作
- 修改Maven配置指向本机安装的路径。
- 导入thymeleaf模板依赖,如果在操作界面有勾选会自动添加依赖。
<!--thymeleaf模板-->
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring5</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-java8time</artifactId>
</dependency>
-
将默认生成的application.properties文件修改yml后yaml文件,yml文件添加配置参数结构清晰。
-
在资源目录下新建i18n目录存放国际化配置文件,并新建show.properties(默认)、show_en_US.properties、show_zh_CN.properties文件
-
新建了en_US文件后,目录会发生变化,可以直接右击Resource Bundle添加配置文件。
可以通过Idea工具下面的视图添加参数。
-
配置yml文件
spring:
messages:
basename: i18n/show
这里配置文件和参数就弄好了。
2.进入到代码编写
- 实现一个国际化资源本地解析接口LocaleResolver。
package com.example.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;
@Configuration
public class MyConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
//这里可以不用去写control类,直接这里实现一样的请求。
registry.addViewController("/show.html").setViewName("show");
}
@Bean
public LocaleResolver localeResolver(){
return new NativeLocaleResolver();
}
protected static class NativeLocaleResolver implements LocaleResolver {
@Override
public Locale resolveLocale(HttpServletRequest request) {
String language = request.getParameter("language");
System.out.println(">>>>language:"+language);
Locale locale = Locale.getDefault();
if(!StringUtils.isEmpty(language)){
String[] split = language.split("_");
locale = new Locale(split[0],split[1]);
}
return locale;
}
@Override
public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {
}
}
}
- 新建测试页面
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8"/>
<title>Title</title>
</head>
<body>
<form action="" method="post">
<label th:text="#{show.test1}"></label>
<label th:text="#{show.test2}"></label>
<br> <br>
<br>
<br> <br>
<a th:href="@{/show.html(language='zh_CN')}">中文</a>
<a th:href="@{/show.html(language='en_US')}">English</a>
</form>
</body>
</html>
- 启动服务进行测试
请求地址:http://localhost:8888/show.html
测试结果:
如果只有show.properties文件,那么就会以默认配置展示。
总结
通过SpringBoot和模版引擎thymeleaf还是能够快速实现国际化资源配置。使用起来更加的方便有效率。