一:什么是模版引擎

模版引擎就是将数据和动态模版页面转成html静态页面。
springboot支持的模版引擎有:FreeMarker、Thymeleaf、jsp、veocity,其中对Freemarker和Thymeleaf支持最友好,其他两个要么性能不好,要么整合起来麻烦。
二:Thymeleaf模版引擎简介
Thymeleaf模版引擎是新一代模版引擎,springboot2.0以下版本使用的是thymeleaf2,springboot2.0版本支持thymeleaf3,thymeleaf3比thymeleaf2在性能方面有很大的改进。
优点:
1:相比jsp页面Thymeleaf页面更简洁,因为没有下面这一堆的东西
|
1
2
3
|
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
|
下面就是Thymeleaf模版页面
|
1
2
3
4
5
6
7
8
9
|
<!DOCTYPE HTML>
<html>
<head>
<title th:text="${error}"></title>
</head>
<body>
</body>
</html>
|
2:标签内容以标签属性渲染,能更好地前后端分离
jsp这么渲染标签内容,这种写法jsp页面脱离工程,页面显示的是${item.name}没法看。
|
1
|
<a target="_blank" href="#">${item.name }</a>
|
Thymeleaf这么渲染标签内容,这种写法页面脱离工程,还可以很好的显示。
|
1
|
<a target="_blank" href="#" th:text="${item.name }">张三</a>
|
综合考虑呢,我们还是选择Thymeleaf模版引擎,使用该模版引擎需要pom依赖
|
1
2
3
4
|
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
|
三:解决标签没闭合报错的问题
1:pom依赖
|
1
2
3
4
5
|
<dependency>
<groupId>net.sourceforge.nekohtml</groupId>
<artifactId>nekohtml</artifactId>
<version>1.9.22</version>
</dependency>
|
2:在application.properties中加如下配置
|
1
|
spring.thymeleaf.mode = LEGACYHTML5
|
解释:spring.thymeleaf.mode的默认值是HTML5,其实是一个很严格的检查,改为LEGACYHTML5可以得到一个可能更友好亲切的格式要求。
四:Thymeleaf视图解析
默认的视图解析:

修改默认视图解析:
|
1
2
3
4
|
spring.thymeleaf.prefix=classpath:/templates/html/ 不要漏写
spring.thymeleaf.suffix=.html
#默认情况下,页面会被浏览器缓存,开发阶段设置为false
spring.thymeleaf.cache=false
|
五:在页面中访问静态资源
静态资源存放目录

页面中这么引入静态文件
|
1
2
3
|
<img src=”/images/….”>
<script src=”/js/….”>
<link href=”/css/….”>
|
注意:无需带上static目录哦。