在上一篇文章“SpringBoot整合視圖技術:Freemarker篇”,與大家分享了SpringBoot應用中如何使用Freemarker模板,今天與大家分享怎麼樣使用Thymeleaf模板。其實過程基本都差不多,我也就不過多廢話咯,直接開整!
1、在pom.xml文件中添加Thymeleaf依賴,如下:
<dependencies>
<!-- web組件 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- thymeleaf組件 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
</dependencies>
2、修改application.yml配置文件,如下:
spring:
thymeleaf:
enabled: true
cache: false #開發環境關閉緩存,生成環境建議開啓緩存
mode: HTML
encoding: UTF-8
prefix: classpath:/templates/
suffix: .html
server:
port: 80
3、在resources目錄下新建templates目錄,並在該目錄下新建我們的測試頁面index.html,其內容如下:
<!doctype html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Thymeleaf測試</title>
</head>
<body>
<h1 th:text="${username}">Thymeleaf 測試</h1>
</body>
</html>
注意:在html標籤中要添加thymeleaf命名空間
xmlns:th="http://www.thymeleaf.org
我有一次就是忘記添加這個,找了好久才找到問題所在,這一步也比較容易忘記,特此在這裏稍作強調!
4、編寫用於測試的控制器ThymeleafController,如下:
/**
* @Description Thymeleaf測試
* @Auther: 笑笑是一個碼農
* @Date: 19:42 2019/11/10
*/
@Controller
public class ThymeleafController {
private static final String INDEX_PAGE = "index";
@GetMapping(value = "/index")
public String index(Map<String, String> map){
map.put("username","笑笑是一個碼農");
return INDEX_PAGE;
}
}
5、最終工程目錄如下:
6、啓動我們的SpringBoot應用,訪問http://localhost/index,如下:
測試成功!
Thymeleaf語法大家可以去官方文檔中看看,在這裏我就不過多介紹啦,官網鏈接:https://www.thymeleaf.org/
源碼地址:
https://github.com/devilyang123/SpringBoot-Learning/tree/master/springboot-thymeleaf
歡迎關注我的個人公衆號“笑笑是一個碼農”,第一時間獲取最新文章。
您的關注,就是支持我持續寫作的最大動力!
還可以免費領取前後端全站學習視頻資料呦~
個人微信號,如需添加微信,請備註來源,因爲媽媽從小就告訴我不要隨便跟陌生人聊天!(嘿嘿~)