1. 国际化

1.1 国际化是什么

国际化(Internationalization,简称i18m):指软件开发应当具备支持多种语言和地区的功能。也就是说能够具备切换页面显示语言的功能。

i18n,其中“I”和“n”分别为首末字符,18 则为中间的字符数

2. 实现国际化

在 Spring Boot 实现国际化的步骤如下:

  1. 编写国际化资源(配置)文件
  2. 利用thymeleaf修改页面
  3. 区域化信息配置

2.1 编写资源文件

资源文件格式:基本名_语言代码_国家或地区代码

我们需要的资源文件包括:

  • messages_zh_CN.properties 中文
  • messages_en_US.properties 英文

1️⃣ Step1:在 resources 目录下新建一个 i18n 目录;

springboot 动态 国际化 springboot国际化原理_java

2️⃣ Step2:在 i18n 目录下新建一个默认的资源文件,比如 massgaes.properties

springboot 动态 国际化 springboot国际化原理_java_02

3️⃣ Step3:在 i18n 目录下新建一个中文资源文件:massages_zh_CN.properties

springboot 动态 国际化 springboot国际化原理_i18n_03

⚠️ 注意:当我们建完这个我呢见我们发现,IDEA自动为我们将配置文件放在 Resource Bundle 目录中,且名为 massages。

4️⃣ Step4:在 Resource Bundle 目录上右键点击 Add Property Files…

springboot 动态 国际化 springboot国际化原理_i18n_04

5️⃣ Step5:添加 en_US

springboot 动态 国际化 springboot国际化原理_spring boot_05

6️⃣ Step6:编写配置的语句,一共写三版:默认显示、中文显示、英文显示,这里就默认显示中文。

springboot 动态 国际化 springboot国际化原理_spring boot_06

🌈 有的版本的IDAE在窗口的左下角会有 TextResource Bundle ,选择 Resource Bundle 进行配置也是一项,我的IDEA版本的2021.2,没找到这个点。

2.2 修改页面

利用 thymeleaf 将每条语句绑定在一起。

1️⃣ Step1:在html中加入thymeleaf;

<html lang="en" xmlns:th="http://www.thymeleaf.org">

2️⃣ Step2:在标签中添加thymeleaf语句

  • 如果文本在标签里面用:th:text="#{massages.xxx}"
  • 如果文本在标签外面用:[[#{massages.xxx}]]

2.3 中英文

利用 a 标签实现中英文的切换。利用thymeleaf指定要调转的页面以及传递的参数。

<a th:href="@{SignUp.html(language='zh_CN')}">中文</a>
<a th:href="@{SignUp.html(language='en_US')}">English</a>

2.4 区域化信息配置

区域化信息配置时实现 LocaleResolver 接口。

LocaleResolver:该组件提供国际化支持,是本地化解析器。

1️⃣ Step1:在项目的Java目录下的 xxxApplication 的同级目录下新建 Config 目录;

2️⃣ Step2:在 Config 目录下新建 MassagesLocalResolver 类,并实现 LocalResolver 接口;

Locale resolveLocale(HttpServletRequest request);
void setLocale(HttpServletRequest request, @Nullable HttpServletResponse response, @Nullable Locale locale);

3️⃣ Step3:实现 resolveLocale 方法;

@Override
    public Locale resolveLocale(HttpServletRequest request) {
        // 获取请求中的语言参数来链接
        String language = request.getParameter("language");
        Locale locale = Locale.getDefault();
        if (!StringUtils.isEmpty(language)) {
            String[] strings = language.split("_");
            locale = new Locale(strings[0], strings[1]);
        }
        return locale;
    }

4️⃣ Step4:在Config目录下新建一个配置类:Boot_Config,实现 WebMvcConfigurer 接口,并实现 localeResolver 方法。

@Configuration
public class Boot_Config implements WebMvcConfigurer {

    @Bean
    public LocaleResolver localeResolver(){
        return new MassagesLocalResolver();
    }

2.4 运行测试

springboot 动态 国际化 springboot国际化原理_spring boot_07

3. 写在最后

实现的接口包括:LocalResolver 、WebMvcConfigurer

  • LocalResolver :默认的解析器,用于设置当前会话的默认国际化语言。
  • WebMvcConfigurer:拦截器,用来对请求的语言参数进行获取,采用默认的LocaleChangeInterceptor 作为拦截器来指定切换国际化语言的参数名。