springboot学习笔记(四)引入themeleaf和国际化配置
webjars:我们需要什么东西,只需要在webjars里面找到相应的pom依赖
https://www.webjars.org/
所有的自动配置规则都在WebMvcAutoConfiguration.java中查找
找到该文件快捷键为ctrl+shift+n(按文件名搜索文件)
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
if (!this.resourceProperties.isAddMappings()) {
logger.debug("Default resource handling disabled");
return;
}
Integer cachePeriod = this.resourceProperties.getCachePeriod();
if (!registry.hasMappingForPattern("/webjars/**")) {
customizeResourceHandlerRegistration(
registry.addResourceHandler("/webjars/**")
.addResourceLocations(
"classpath:/META-INF/resources/webjars/")
.setCachePeriod(cachePeriod));
}
- “/**”访问当前项目得任何资源,(静态)
“classpath:/META-INF/resources/”
"classpath:/resources/"
"classpath:/static/"
"classpath:/public/"
"/":当前项目得根路径
那么我们就只能用默认的静态资源文件夹嘛?当然不是的,我们可以在application.properties中配置我们自己得静态资源文件夹目录:
spring.resources.static-location=classpath:/hello/,classpath:/xxx/
引入thymeleaf模板引擎
springboot使用了内置得tomcat,且默认是不支持jsp得,所以我们如果使用纯静态的html来写前端页面,就会使得开发量等很麻烦
这里我们使用springboot官方推荐得模板引擎thymeleaf:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<thymeleaf.version>3.0.9.RELEASE</thymeleaf.version>
<thymeleaf-layout-dialect.version>2.2.2</thymeleaf-layout-dialect.version>
国际化配置
一个网页实现中英文的切换就要用到我们的国际化.要实现国际化分为这么四步:
- 首先在resources下创建文件夹i18n
- 在该文件夹下创建国际化配置文件(例如login.properties)
创建一个properties文件 login.properties 和一个login_zh_CN.properties注意这里的’_zh_CN不能改变!’
编写我们要国际化的值.
2.SpringBoot自动配置好了管理国际化资源文件的组件;
@ConfigurationProperties(prefix = "spring.messages")
public class MessageSourceAutoConfiguration {
/**
* Comma-separated list of basenames (essentially a fully-qualified classpath
* location), each following the ResourceBundle convention with relaxed support for
* slash based locations. If it doesn't contain a package qualifier (such as
* "org.mypackage"), it will be resolved from the classpath root.
*/
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;
}
springBoot帮我们配置好了国际化的配置,我们只需要在springBoot的配置文件中加入是在哪一个包下的–>spring.messages.basename=i18n.login
一般我们都会把国际化的配置放在i18n下.
3.去页面获取国际化的值
<body class="text-center">
<form class="form-signin" action="dashboard.html">
<img class="mb-4" src="asserts/img/bootstrap-solid.svg" th: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>
<label class="sr-only" th:text="#{login.username}">Username</label>
<input type="text" class="form-control" placeholder="Username" th:placeholder="#{login.username}" required="" autofocus="">
<label class="sr-only" th:text="#{login.password}">Password</label>
<input type="password" class="form-control" placeholder="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>
效果:根据浏览器语言设置的信息切换了国际化;
原理:
国际化Locale(区域信息对象);LocaleResolver(获取区域信息对象)
@Bean
@ConditionalOnMissingBean
@ConditionalOnProperty(prefix = "spring.mvc", name = "locale")
public LocaleResolver localeResolver() {
if (this.mvcProperties
.getLocaleResolver() == WebMvcProperties.LocaleResolver.FIXED) {
return new FixedLocaleResolver(this.mvcProperties.getLocale());
}
AcceptHeaderLocaleResolver localeResolver = new AcceptHeaderLocaleResolver();
localeResolver.setDefaultLocale(this.mvcProperties.getLocale());
return localeResolver;
}
默认的就是根据请求头带来的区域信息获取Locale进行国际化
public class MyLocaleResolver implements LocaleResolver {
@Override
public Locale resolveLocale(HttpServletRequest request) {
String l = request.getParameter("l");
// 获取默认的区域信息
Locale locale=Locale.getDefault();
if(!StringUtils.isEmpty(l)){
String[] split = l.split("_");
locale= new Locale(split[0], split[1]);
}
return locale;
}
@Override
public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {
}
}
注意把我们的这个配置组件注册到spring的容器中来
@Bean
public LocaleResolver localeResolver(){
return new MyLocaleResolver();
}
点击切换就可也切换中,英文了.
效果图:
点击中文
英文: