前面章節咱們介紹了SpringBoot集成jsp和Freemarker以及它們的具體應用。而在這些前端模板引擎中,SpringBoot首推使用Thymeleaf。這是由於Thymeleaf對SpringMVC提供了完美的支持。html
Thymeleaf一樣是一個Java類庫,可以處理HTML/HTML五、XML、JavaScript、CSS,甚⾄純⽂本。一般能夠用做MVC中的View層,它能夠徹底替代JSP。前端
與其餘模板引擎相比,Thymeleaf不會破壞文檔結構。對比Freemarker能夠看出效果:web
FreeMarker: <p>${message}</p> Thymeleaf: <p th:text="${message}">Hello World!</p>
注意,因爲Thymeleaf使用了XML DOM解析器,所以它並不適合於處理大規模的XML文件。spring
SpringBoot中建立項目並集成Thymeleaf。建立過程當中勾選對應集成框架。segmentfault
項目建立以後,pom中對應的核心依賴以下:瀏覽器
<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> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> </dependency>
實體類Student:緩存
@Data public class Student { private String idNo; private String name; }
Controller對應實現:微信
@Controller public class StudentController { @GetMapping("/") public String getStudents(Model model){ List<Student> list = new ArrayList<>(); Student s1 = new Student(); s1.setIdNo("N01"); s1.setName("Tom"); list.add(s1); Student s2 = new Student(); s2.setIdNo("N02"); s2.setName("David"); list.add(s2); model.addAttribute("students",list); model.addAttribute("hello","Hello Thymeleaf!"); return "student"; } }
在Controller中實現了兩個參數的返回一個爲字符串,一個爲Student的列表。app
對應templates下的頁面爲student.html。Thymeleaf默認使用html做爲後綴。框架
student.html頁面展現信息以下:
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"/> <title>Hello Thymeleaf</title> </head> <body> <h1 th:text="${hello}">Hello World</h1> <div th:each="student : ${students}"> <p th:text="${student.name} + ':' + ${student.idNo}"></p> </div> </body> </html>
其中第一個爲直接展現字符串,第二個爲遍歷列表並展現其中的屬性值。
訪問對應請求http://localhost:8080/,便可返內容展現。
若是是在開發環境中,最好在application.properties中添加配置:
spring.thymeleaf.cache=false
關閉Thymeleaf的緩存(默認爲true),避免因緩存致使修改需重啓才能生效,生產環境可採用默認值。
使用Thymeleaf的頁面必須在HTML標籤中做以下聲明,表示使用Thymeleaf語法:
<html xmlns:th="http://www.thymeleaf.org">
SpringBoot中提供了大量關於Thymeleaf的配置項目:
# 開啓模板緩存(默認值:true) spring.thymeleaf.cache=true # 檢查模板是否存在 spring.thymeleaf.check-template=true # 檢查模板位置是否正確(默認值:true) spring.thymeleaf.check-template-location=true # Content-Type的值(默認值:text/html) spring.thymeleaf.content-type=text/html # 開啓MVC Thymeleaf視圖解析(默認值:true) spring.thymeleaf.enabled=true # 模板編碼 spring.thymeleaf.encoding=UTF-8 # 排除視圖名稱列表,用逗號分隔 spring.thymeleaf.excluded-view-names= # 模板模式,設置爲HTML5會嚴格校驗,不符合規則將報錯 spring.thymeleaf.mode=HTML5 # 視圖名稱前綴(默認值:classpath:/templates/) spring.thymeleaf.prefix=classpath:/templates/ # 視圖名稱後綴(默認值:.html) spring.thymeleaf.suffix=.html # 可解析的視圖名稱列表,用逗號分隔 spring.thymeleaf.view-names=
關於SpringBoot集成Thymeleaf的操做已經完成,很是簡單。
<center>程序新視界:精彩和成長都不容錯過</center>