国际化(internationalization)是设计和制造容易适应不同区域要求的产品的一种方式。它要求从产品中抽离所有地域语言,国家/地区和文化相关的元素。换言之,应用程序的功能和代码设计考虑在不同地区运行的需要,其代码简化了不同本地版本的生产。开发这样的程序的过程,就称为国际化。
那么当我们使用Spring Boot如何进行国际化呢?那么当你读完这篇文章你会学到如下知识:
(1) spring boot 加入thymeleaf;
(2) 页面元素国际化;
(3) spring boot默认国际化原理说明;
(4) firefox浏览器修改区域语言;
(5)chrome浏览器修改区域语言;
(6)修改默认messages配置前缀;
(7) 代码中如何获取国际化信息;
(8) 优化代码获取国际化信息;
(9) 区域解析器之AcceptHeaderLocaleResolver;
(10) 会话区域解析器之SessionLocaleResolver;
(11) Cookie区域解析器之CookieLocaleResolver;
(12)固定的区域解析器之FixedLocaleResolver ;
(13)使用参数修改用户的区域;
接下里我们看看这些具体应该怎么操作。
(1) spring boot 加入thymeleaf;
Spring boot集成thymeleaf在http://www.vxzsk.com/440.html
这篇文章有介绍过,所以这里就不过多进行介绍了。在这里我们为之后的讲解做点基本准备。
模板文件resources/templates/hello.html :
1
2
3
4
5
6
7
8
9
10
11
12
|
<!DOCTYPE html>
<
html
>
<
head
>
<
meta
charset
=
"UTF-8"
/>
<
title
>hello spring boot</
title
>
</
head
>
<
body
>
<
p
>欢迎你登录到阿里巴巴网站</
p
>
</
body
>
</
html
>
|
这里没有特殊的代码,访问就是显示一些文字,这里还没加入国际化的相关东西,之后添加。
编写访问地址:com.kfit.controller.HelloController:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
package
com.kfit.controller;
import
org.springframework.stereotype.Controller;
import
org.springframework.web.bind.annotation.RequestMapping;
@Controller
public
class
HelloController {
@RequestMapping
(
"/hello"
)
public
String hello(){
return
"/hello"
;
}
}
|
这里就是访问http://127.0.0.1:8080/hello就跳转到hell.html进行访问。
到这里准备工作就好了。
(2) 页面元素国际化;
我们观察hello.html里面的信息直接就是中文显示,所以我们现在的需求是当访问语言是zh的时候显示为中文,当语言为en的时候显示为英文,那么怎么操作呢?
首先我们先定义国际化资源文件,spring boot默认就支持国际化的,而且不需要你过多的做什么配置,只需要在resources/下定义国际化配置文件即可,注意名称必须以messages开发。
我们定义如下几个文件:
messages.properties (默认,当找不到语言的配置的时候,使用该文件进行展示)。
messages_zh_CN.properties(中文)
messages_en_US.properties(英文)
具体的代码如下:
messages.properties:
welcome = 欢迎你登录到 阿里巴巴 网站(default)
messages_zh_CN.properties:
1
|
welcome = \u6b22\u8fce\u4f60\u767b\u5f55\u5230 \u963f\u91cc\u5df4\u5df4 \u7f51\u7ad9\uff08\u4e2d\u6587\uff09
|
对应的信息是:
welcome = 欢迎你登录到 阿里巴巴 网站(中文)
messages_en_US.properties:
1
|
welcome = welcome to login to alibaba website(English)
|
配置信息就这么简单,那么在前端展示怎么修改呢,修改hello.html文件,使用#{key}的方式进行使用messages中的字段信息:
1
2
3
4
5
6
7
8
9
10
|
<!DOCTYPE html>
<
html
>
<
head
>
<
meta
charset
=
"UTF-8"
/>
<
title
>hello spring boot</
title
>
</
head
>
<
body
>
<
p
><
label
th:text
=
"#{welcome}"
></
label
></
p
>
</
body
>
</
html
>
|
重新访问:http://127.0.0.1:8080/hello 应该显示:
欢迎你登录到 阿里巴巴 网站(中文)
(3) spring boot默认国际化原理说明
在这里我们先打住下,简单说下原理:
第一个问题,为什么命名必须是messages开头,需要看一个源码文件:
org.springframework.boot.autoconfigure.MessageSourceAutoConfiguration:
这里提取部分代码: