一、pom 檔案引入Thymeleaf
在原 SpringBoot 項目中的 POM 檔案中加入 Thymeleaf 坐标,如果不知道坐标可以從 Maven 中央庫查詢 http://mvnrepository.com/。當然,如果項目沒有使用 Maven ,那就需要導入 Thymeleaf 的Jar ,包括有 thymeleaf-spring5.jar ,和 thymeleaf-extras-java8time.jar。
<!-- 引入thymeleaf的依賴包. -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
二、Controller
package com.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* @Description springboot整合Thymeleaf
* @author 歐陽
* @since 2019年4月10日 下午5:20:49
* @version V1.0
*/
@Controller
public class IndexThymeleafController {
@RequestMapping("/indexThymeleaf")
public String indexThymeleaf(Model model) {
model.addAttribute("title", "springboot整合Thymeleaf");
return "indexThymeleaf";
}
}
注意:使用注解
@Controller
而不要使用
@RestController
,否則會将傳回的視圖名解析成字元串傳回到頁面。如果使用
@RestController
注解,則需要傳回
ModelAndView
。
三、application.properties 配置
在
application.properties
檔案中添加下面配置:
### Thymeleaf Configuration
spring.thymeleaf.cache=true
spring.thymeleaf.enable-spring-el-compiler=true
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.servlet.content-type=text/html; charset=utf-8
spring.thymeleaf.check-template-location=true
spring.thymeleaf.check-template=true
spring.thymeleaf.suffix=.ftl
上面的配置使用
application.yml
檔案配置如下:
### Thymeleaf Configuration
spring:
thymeleaf:
cache: true
enable-spring-el-compiler: true
encoding: UTF-8
suffix: .html
check-template-location: true
check-template: true
servlet:
content-type: text/html; charset=utf-8
其實也可以不用添加配置,大部分用到的架構已經預設打開了,這裡隻是為了示範如果需要配置則按需配置,例如:如果模闆需要用到 EL 表達式,則需要将
spring.thymeleaf.enable-spring-el-compiler
配置為 true(支援)因為spring的 EL 表達式預設是 false(不支援)。
四、HTML 檔案
當使用 Thymeleaf 模闆引擎時,預設的模闆配置路徑為:
src/main/resources/templates
,下面是使用預設的模闆配置路徑建立檔案
indexThymeleaf.html
,其的主要代碼如下所示。關于 Thymeleaf 的文法請參考文章 SpringBoot學習——Thymeleaf教程詳解。
<body>
<h3 th:text="${title}"></h3>
</body>
五、整合後結果
浏覽器通路位址:http://localhost:8080/indexThymeleaf ,後效果圖如下:
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIyROBlL0kjM1ADOzcTMwEDNwkTMwIzLc52YucWbp5GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.png)