form1.cn
Make a little progress every day

thymeleaf获取配置properties中的数据与thymeleaf国际化

07th of August 2017 Java Java 12557

有时候会有直接在模板中获取配置文件properties中的配置信息,比如:webname = form1,不需要用java传给模板,在模板中就可以直接获取的方法


使用thymeleaf提供的国际化


首先我们先定义国际化资源文件,spring boot默认就支持国际化的,而且不需要你过多的做什么配置,只需要在resources/下定义国际化配置文件即可,注意名称必须中messages开始,要不然识别不了,因为springboot默认将国际化的配置文名称定义为messages,当然你也可以改变这个默认的配置


我们定义如下几个文件:

messages.properties (默认,当找不到语言的配置的时候,使用该文件进行展示)。
messages_zh_CN.properties(中文)
messages_en_US.properties(英文)


具体的代码如下:

messages.properties:
welcome = 欢迎你登录form1.cn网站(default)

messages_zh_CN.properties:
welcome = \u6b22\u8fce\u4f60\u767b\u5f55\u5230 \u963f\u91cc\u5df4\u5df4 \u7f51\u7ad9\uff08\u4e2d\u6587\uff09 #unicode

messages_en_US.properties:
welcome = welcome to login to form.cn website(English)


修改hello.html文件,使用#{key}的方式进行使用messages中的字段信息:

<!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 应该显示:


欢迎你登录到form1.cn网站(中文)


如果网站没有多语言的需求,那么就做一个 messages.properties 来放自己的一些配置


注:如果你的messages.properties中文乱码,那么 对工程进行 settings 找到 File Encodings 然后改为utf-8即可