SpringBoot----国际化配置的原理和操作——配置国际化文件27

国际化

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的全局默认配置重写设置,然后重写国际化配置文件的信息。


 

 

 
 

 

 
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值