国际化
1.编写国际化配置文件
2.使用ResourceBundleMessageSource管理国际化资源文件(SpingBoot已经默认自动配置了)
3.在页面使用fmt:message取出国际化内容(这里我用的是thymeleaf引擎取数据)
操作:简单示例
第一步:
在项目的resources资源文件包里面添加i18n包,在包下添加三个配置文件(文件名里面包含了语言编号和国家编号)
第二步:
编写配置文件内容
1.打开配置文件
2.点击Resource Bundle(IDEA工具)
3.编写需要国际化的内容(如下图)
第三步:
1.原理说明
SpringBoot已经自动配置好了国际化的组件
MessageSourceAutoConfiguration自动配置类,里面的MessageSourceProperties参数类获取默认配置,而messageSource方法向容器返回一个messageSource组件。
messageSource方法功能:
设置国际化资源文件的基础名(比如上面配置文件名一开头的login),点击查看参数类看到下面的注释
上面的意思是如果不配置基础名,那么就从项目的classpath目录下找文件名开头为“message”的properties配置文件.
2.操作
在application.yml里面配置
spring:
messages:
basename: i18n.login
第四步:
thymeleaf引擎取出国际化的数据如下的例子,thymeleaf有专门取国际化数据的语法
<body class="text-center">
<form class="form-signin" action="dashboard.html" th:action="@{/user/login}" method="post">
<img class="mb-4" th:src="@{/asserts/img/bootstrap-solid.svg}" src="asserts/img/bootstrap-solid.svg" alt="" width="72" height="72">
<h1 class="h3 mb-3 font-weight-normal" th:text="#{login.tip}">Please sign in</h1>
<!--判断-->
<p style="color: red" th:text="${msg}" th:if="${not #strings.isEmpty(msg)}"></p>
<label class="sr-only" th:text="#{login.username}">Username</label>
<input type="text" class="form-control" name="username" th:placeholder="#{login.username}" placeholder="Username" required="" autofocus="">
<label class="sr-only" th:text="#{login.password}">Password</label>
<input type="password" class="form-control" placeholder="Password" name="password" th:placeholder="#{login.password}" required="">
<div class="checkbox mb-3">
<label>
<input type="checkbox" value="remember-me" > [[#{login.remember}]]
</label>
</div>
<button class="btn btn-lg btn-primary btn-block" type="submit" th:text="#{login.btn}">Sign in</button>
<p class="mt-5 mb-3 text-muted">© 2017-2018</p>
<a class="btn btn-sm" th:href="@{/index.html(l='zh_CN')}" >中文</a>
<a class="btn btn-sm" th:href="@{/index.html(l='en_US')}" >English</a>
</form>
</body>
第五步:
1.运行项目打开做了国际化的页面然后,浏览器会根据默认的语言优先级设置在请求的时候设置http请求头的Accept-Language
2.如果乱码了还需要在IDEA的全局默认配置重写设置,然后重写国际化配置文件的信息。