前端提交的往往只是html页面,在此基础上需要我们转为一些模板引擎来进行操作,在这之前熟悉的jsp就是一个模板引擎,同时它也是个servlet。但是springBoot不支持jsp模板引擎。所以对于Thymeleaf的学习就很有必要。是一个高级语言的模板引擎,他的这个语法更简单。
1、引入Thymeleaf
在SpringBoot中都是start一下就够了,其中需要去Thymeleaf官网:https://www.thymeleaf.org/
找到对应的pom依赖:
<!--thymeleaf-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
Thymeleaf模板引擎分析:
首先得按照SpringBoot的自动装配原理看一下该Thymeleaf的自动装配规则。
Thymeleaf的自动配置类:ThymeleafProperties
@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";
private Charset encoding;
}
html页面放在类路径下的templates下,thymeleaf就可以实现自动渲染了。
可以写一个简单的demo演示,controller test.html等等 记住test.html放在templates目录下。
至于 thymeleaf 的语法学习可以参考官方文档或者视频解读。