[toc]
SpringBoot整合Thymeleaf
零、本片要點(diǎn)
- 介紹Thymeleaf的概念,理解Thymeleaf的便利且強(qiáng)大。
- 介紹如何快速整合SpringBoot和Thymeleaf。
- 介紹自動(dòng)配置原理。
一、Thymeleaf簡介
Thymeleaf是適用于Web和獨(dú)立環(huán)境的現(xiàn)代服務(wù)器端Java模板引擎,能夠處理HTML,XML,JavaScript,CSS甚至純文本。
Thymeleaf的主要目標(biāo)是提供一種優(yōu)雅且高度可維護(hù)的模板創(chuàng)建方法。拿Html為例,它支持html原型,既可以讓美工在瀏覽器查看頁面的靜態(tài)效果,也可以讓開發(fā)者填充后端數(shù)據(jù)。
二、快速啟動(dòng)
- 需要引入thymeleaf需要的依賴,以及必要的web依賴。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
- SpringBoot針對(duì)Thymeleaf提供了一套優(yōu)秀的自動(dòng)配置方案,這一套配置類的屬性在
org.springframework.boot.autoconfigure.thymeleaf.ThymeleafProperties,部分源碼如下:
// 將application.properties前綴為【spring.thymeleaf】的配置和屬性綁定
@ConfigurationProperties(prefix = "spring.thymeleaf")
public class ThymeleafProperties {
//默認(rèn)的編碼格式
private static final Charset DEFAULT_ENCODING = StandardCharsets.UTF_8;
//默認(rèn)視圖解析器前綴
public static final String DEFAULT_PREFIX = "classpath:/templates/";
//默認(rèn)視圖解析器后綴
public static final String DEFAULT_SUFFIX = ".html";
private boolean checkTemplate = true;
private boolean checkTemplateLocation = true;
private String prefix = DEFAULT_PREFIX;
private String suffix = DEFAULT_SUFFIX;
private String mode = "HTML";
private Charset encoding = DEFAULT_ENCODING;
private boolean cache = true;
//...
不難發(fā)現(xiàn),如果開發(fā)者不配置前綴和后綴,視圖解析的默認(rèn)位置會(huì)在resources/templates/目錄下,且文件后綴為.html。SpringBoot的強(qiáng)大之處就是提供了我們?cè)S多配置上的便利,比如,我們可以很容易地關(guān)閉Thymeleaf的緩存,在application.properties:
spring.thymeleaf.cache=false
SpringBoot為Thymeleaf提供的自動(dòng)化配置類是:
@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties(ThymeleafProperties.class)
@ConditionalOnClass({ TemplateMode.class, SpringTemplateEngine.class })
@AutoConfigureAfter({ WebMvcAutoConfiguration.class, WebFluxAutoConfiguration.class })
public class ThymeleafAutoConfiguration {
}
可以看到,這個(gè)配置類首先導(dǎo)入了ThymeleafProperties配置類,然后通過@ConditionalOnClass注解標(biāo)識(shí)這個(gè)類只有系統(tǒng)中存在TemplateMode和SpringTemplateEngine的時(shí)候才會(huì)生效,其實(shí)也就是引入了Thymeleaf相關(guān)依賴就會(huì)生效。
- 創(chuàng)建測試Controller
@Controller
public class HelloController {
@GetMapping("/")
public String index(ModelMap map){
map.addAttribute("url","/list");
map.addAttribute("msg","點(diǎn)我點(diǎn)我");
return "index";
}
}
@GetMapping("/list")
public String list(Model model){
List<User> users = new ArrayList<>();
users.add(new User(UUID.randomUUID().toString(),"summerday",20));
users.add(new User(UUID.randomUUID().toString(),"天喬巴夏",18));
model.addAttribute("users",users);
return "list";
}
由于我們并沒有修改過視圖解析的配置,我們需要在/resources/templates/提供名為index.html和list.html的文件。
- 編寫Thymeleaf模板
<!--index.html-->
<!DOCTYPE html>
<!--suppress ALL-->
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Hello</title>
</head>
<body>
<!-- thymeleaf通過th標(biāo)簽增強(qiáng)屬性,最終通過標(biāo)簽中的內(nèi)容覆蓋原有標(biāo)簽內(nèi)容-->
<a th:href="${url}"><p th:text="${msg}"></p> </a>
</body>
</html>
<!--list.html-->
<!DOCTYPE html>
<!--suppress ALL-->
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>list</title>
</head>
<body>
<h3>for each</h3>
<!--說明: th:each="obj,stat:${objects}" 分別代表單個(gè)實(shí)例,狀態(tài)(可省略),待遍歷對(duì)象-->
<div th:each="user,stat:${users}">
<input type="hidden" name="id" th:value="${user.id}"/>
姓名:<input type="text" name="username" th:value="${user.username}"/>
年齡:<input type="text" name="age" th:value="${user.age}"/>
索引: <input type="text" th:value="${stat.index}">
</div>
</body>
</html>
list頁面渲染結(jié)果如下:

除此之外,Thymeleaf還支持使用js獲取Model中的變量:
<script th:inline="javascript">
var msg = [[${msg}]];
console.log(msg)
</script>
三、源碼下載
本文主要介紹了SpringBoot整合Thymeleaf自動(dòng)配置的原理,以及快速啟動(dòng)demo項(xiàng)目需要的步驟。關(guān)于Thymeleaf本身,還有其他許多強(qiáng)大的用法,可以參照官方文檔,一一測試:https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html
另外,本文的樣例代碼【包括其他基礎(chǔ)標(biāo)簽的使用】均已上傳至Gitee:https://gitee.com/tqbx/springboot-samples-learn