Thymeleaf的导入
模板引擎:因使用boot时,用的是内置的tomcat,默认是不支持jsp,故无法使用将html转成jsp的方法来动态处理前端数据。
Thymeleaf模板引擎:
springboot推荐使用Thymeleaf模板引擎。其实jsp就是一个模板引擎,模板引擎有很多,不止jsp,thymeleaf。
模板引擎的作用就是我们来写一个页面模板,比如有些值呢,是动态的,我们写一些表达式。而这些值,从哪来呢,就是我们在后台封装一些数据。然后把这个模板和这个数据交给我们模板引擎,模板引擎按照我们这个数据帮你把这表达式解析、填充到我们指定的位置,然后把这个数据最终生成一个我们想要的内容给我们写出去,这就是我们这个模板引擎,不管是jsp还是其他模板引擎,都是这个思想。只不过呢,就是说不同模板引擎之间,他们可能这个语法有点不一样。其他的我就不介绍了,我主要来介绍一下SpringBoot给我们推荐的Thymeleaf模板引擎,这模板引擎呢,是一个高级语言的模板引擎,他的这个语法更简单。而且呢,功能更强大。
此图引用狂神
Thymeleaf模板引擎的引用
找到对应的pom依赖,导入即可。
<!--thymeleaf-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
版本问题:如果springboot使用的为1.x,则Thymeleaf模板引擎使用2.x,boot使用的为2.x,则Thymeleaf模板引擎使用3.x,否则会报错
前面呢,我们已经引入了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就可以帮我们自动渲染了。使用thymeleaf什么都不需要配置,只需要将他放在指定的文件夹下即可!