Spring Boot小记(9)

thymeleaf

作者 Wavy Peng 日期 2018-05-06
Spring Boot小记(9)

基本概念

使用Spring Boot

1、创建Spring Boot应用,选中需要的模块

2、Spring Boot默认将这些场景配置好了,只需要在配置文件中指定少量配置就可运行

3、编写业务代码

自动配置原理?

这个场景Spring Boot帮助我们配置了什么?能不能修改?能修改哪些配置?能不能扩展?…

xxxxAutoConfiguration:帮我们给容器中自动配置组件
xxxxProperties:配置类来封装配置文件的内容

Spring Boot对静态资源的映射规则

Spring Boot中添加资源映射的源码:

@ConfigurationProperties(
prefix = "spring.resources",
ignoreUnknownFields = false
)
public class ResourceProperties {
//可以设置和静态资源有关的参数,如缓存时间等
public void addResourceHandlers(ResourceHandlerRegistry registry) {
if(!this.resourceProperties.isAddMappings()) {
logger.debug("Default resource handling disabled");
} else {
Duration cachePeriod = this.resourceProperties.getCache().getPeriod();
CacheControl cacheControl = this.resourceProperties.getCache().getCachecontrol().toHttpCacheControl();
if(!registry.hasMappingForPattern("/webjars/**")) {
this.customizeResourceHandlerRegistration(registry.addResourceHandler(new String[]{"/webjars/**"}).addResourceLocations(new String[]{"classpath:/META-INF/resources/webjars/"}).setCachePeriod(this.getSeconds(cachePeriod)).setCacheControl(cacheControl));
}

String staticPathPattern = this.mvcProperties.getStaticPathPattern();
if(!registry.hasMappingForPattern(staticPathPattern)) {
this.customizeResourceHandlerRegistration(registry.addResourceHandler(new String[]{staticPathPattern}).addResourceLocations(getResourceLocations(this.resourceProperties.getStaticLocations())).setCachePeriod(this.getSeconds(cachePeriod)).setCacheControl(cacheControl));
}

}
}


//配置欢迎页映射
@Bean
public WelcomePageHandlerMapping welcomePageHandlerMapping(ApplicationContext applicationContext) {
return new WelcomePageHandlerMapping(new TemplateAvailabilityProviders(applicationContext), applicationContext, this.getWelcomePage(), this.mvcProperties.getStaticPathPattern());
}

分析:

1、所有/webjars/**下的请求,都去classpath:/META-INF/resources/webjars/下找资源。

webjars:以jar包的方式引入静态资源。相关网址

以jquery为例,其结构目录如下:

webjars

pom.xml中引入如下依赖:

<!-- 引入jquery-webjars -->
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>3.3.1-1</version>
</dependency>

在访问时只需要写webjars下面资源的名称即可

比如通过localhost:8080/webjars/jquery/3.3.1-1/jquery.js即可访问下面jquery.js文件

2、/**访问当前项目的任何资源(静态资源的文件夹)

"classpath:/META-INF/resources/", 类路径下的/META-INF/resources
"classpath:/resources/", 类路径下的/resources
"classpath:/static/", 类路径下的/static
"classpath:/public/" 类路径下的/public
"/":当前项目的根路径

/java//resources/是类路径(classpath)的根路径。

访问规则:localhost:8080/abc === 到静态资源文件夹里找abc

3、欢迎页,静态资源文件夹下的所有index.html页面,被/**映射

localhost:8080/ 找index页面

private Resource getIndexHtml(String location) {
return this.resourceLoader.getResource(location + "index.html");
}

4、所有的**/favicon.ico都是在静态资源文件下找

@Configuration
@ConditionalOnProperty(
value = {"spring.mvc.favicon.enabled"},
matchIfMissing = true
)
public static class FaviconConfiguration implements ResourceLoaderAware {
... ...
@Bean
public SimpleUrlHandlerMapping faviconHandlerMapping() {
SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
mapping.setOrder(-2147483647);
mapping.setUrlMap(Collections.singletonMap("**/favicon.ico", this.faviconRequestHandler()));
return mapping;
}
... ...
}

模板引擎

工作原理

模板引擎

Spring Boot推荐使用Thymeleaf,语法简单,功能强大

使用方法

1、引入thymeleaf

<!-- 引入thymeleaf -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

<!-- 切换thymeleaf版本 -->
<properties>
<thymeleaf.version>3.0.9.RELEASE</thymeleaf.version>
<!-- 布局功能的支持程序,thymeleaf3主程序 layout2以上版本 -->
<!-- thymeleaf2 layout1-->
<thymeleaf-layout-dialect.version>2.2.2</thymeleaf-layout-dialect.version>
</properties>

2、Thymeleaf使用&语法

@ConfigurationProperties(
prefix = "spring.thymeleaf"
)
public class ThymeleafProperties {
private static final Charset DEFAULT_ENCODING;
public static final String DEFAULT_PREFIX = "classpath:/templates/";
public static final String DEFAULT_SUFFIX = ".html";
private boolean checkTemplate = true;
private boolean checkTemplateLocation = true;
private String prefix = "classpath:/templates/";
private String suffix = ".html";
private String mode = "HTML";

说明:只要将HTML页面放在classpath:/templates/,thymeleaf就能自动渲染

1、导入thymeleaf的名称空间

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

2、使用thymeleaf语法

<!-- th:text 设置div里面的文本内容-->
<div th:text="${hello}"></div>

语法规则

th:text 改变当前元素里面的文本内容

th:任意html属性,来替换原生属性的值

th属性

表达式

Simple expressions:(表达式语法)
Variable Expressions: ${...} #获取变量值,OGNL
说明:
1)获取对象的属性、调用方法
2)使用内置的基本对象:
#ctx: the context object.
#vars: the context variables.
#locale: the context locale.
#request: (only in Web Contexts) the HttpServletRequest object.
#response: (only in Web Contexts) the HttpServletResponse object.
#session: (only in Web Contexts) the HttpSession object.
#servletContext: (only in Web Contexts) the ServletContext object.
3)内置的一些工具对象

Selection Variable Expressions: *{...} #选择表达式,和${}在功能上是一样的
说明:配合th:object="${session.user}"

Message Expressions: #{...} #获取国际化内容

Link URL Expressions: @{...} #定义URL
举例:@{/order/process(execId=${execId},execType='FAST')}

Fragment Expressions: ~{...} #片段引用表达式
举例:<div th:insert="~{commons :: main}">...</div>

Literals: (字面量)
Text literals: 'one text', 'Another one!',…
Number literals: 0, 34, 3.0, 12.3,…
Boolean literals: true, false
Null literal: null
Literal tokens: one, sometext, main,…

Text operations: (文本操作)
String concatenation: +
Literal substitutions: |The name is ${name}|

Arithmetic operations: (数学运算)
Binary operators: +, -, *, /, %
Minus sign (unary operator): -

Boolean operations: (布尔运算)
Binary operators: and, or
Boolean negation (unary operator): !, not

Comparisons and equality: (比较运算)
Comparators: >, <, >=, <= (gt, lt, ge, le)
Equality operators: ==, != (eq, ne)

Conditional operators: (条件运算)
If-then: (if) ? (then)
If-then-else: (if) ? (then) : (else)
Default: (value) ?: (defaultvalue)

Special tokens:
No-Operation: _