Spring boot 国际化——完美向导

   说明: idea环境,导入thymeleaf的maven。

1.编写国际化配置文件

    在resource目录下,创建一个i18n的文件夹(名字随便写了)

    

     在i18n目录下创建一个login.properties(这个是默认的文件) login_zh_CN.properties(中文) , login_en_US.properties(英文)  

         

     根据你前端的的 编写,这里以登录用户和密码为例:

      

     

2.SpringBoot自动配置好了管理国际化资源文件的组件(这是底层的源码)

@ConfigurationProperties(prefix = "spring.messages")
public class MessageSourceAutoConfiguration {
    private String basename = "messages";  
    //我们的配置文件可以直接放在类路径下叫messages.properties;

    @Bean
	public MessageSource messageSource() {
		ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
		if (StringUtils.hasText(this.basename)) {
            //设置国际化资源文件的基础名(去掉语言国家代码的)
			messageSource.setBasenames(StringUtils.commaDelimitedListToStringArray(
					StringUtils.trimAllWhitespace(this.basename)));
		}
		if (this.encoding != null) {
			messageSource.setDefaultEncoding(this.encoding.name());
		}
		messageSource.setFallbackToSystemLocale(this.fallbackToSystemLocale);
		messageSource.setCacheSeconds(this.cacheSeconds);
		messageSource.setAlwaysUseMessageFormat(this.alwaysUseMessageFormat);
		return messageSource;
	}

既然spring boot 都帮我配置好了,那我们就在application.properties加入。

spring.messages.basename=i18n.login  

3.去页面获取国际化的值。

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

	<body class="text-center">
		<form class="form-signin" action="dashboard.html">
			<img class="mb-4" src="asserts/img/bootstrap-solid.svg" alt="" width="72" height="72">
             <!--标题通过thymeleaf的表达式th:text="#{login.tip}"获取的,
                 表达式login.tip 就是刚才设置好的值。其他的以此类推。
            -->
			<h1 class="h3 mb-3 font-weight-normal" th:text="#{login.tip}">Please sign in</h1>
			<label class="sr-only" th:text="#{login.username}">Username</label>
			<input type="text" class="form-control"  placeholder="Username" required="" autofocus="">
			<label class="sr-only" th:text="#{login.password}">Password</label>
			<input type="password" class="form-control" placeholder="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">中文</a>
			<a class="btn btn-sm">English</a>
		</form>

	</body>

4.测试

  

 

     通过Google设置--语言.进行置顶。

我是程序员s,欢迎一起交流。

猜你喜欢

转载自blog.csdn.net/u012448904/article/details/81234845