? Thymeleaf是SpringBoot官方推薦的用來渲染頁面的一個模板孵稽,如果你對模板和模板引擎沒什么概念的話,可以簡單理解為Thymeleaf是一個高級簡潔的JSP十偶。如果學(xué)過MVC設(shè)計模式菩鲜,那么Thymeleaf就是視圖層(view)的主要核心內(nèi)容辆布。
為什么要整合Thymeleaf
- SpringBoot在內(nèi)置Tomcat服務(wù)器蕾总,并且以Jar包方式運行顾稀,傳統(tǒng)JSP頁面不在適合這種模式開發(fā)
- 使用Thymeleaf有助于前后端協(xié)作缎浇,因為它在無網(wǎng)絡(luò)環(huán)境下也可以運行媚污,前端開發(fā)者便于在靜態(tài)頁面查看頁面效果,后臺開發(fā)者也便于在服務(wù)器查看實時的數(shù)據(jù)交互儡司。
- 實現(xiàn)嚴格的mvc設(shè)計模式嘉竟,不用像JSP頁面大量嵌套Java代碼,開發(fā)更簡潔
整合Thymeleaf過程及步驟
首先诽凌,明確整合Thymeleaf需要用到模塊依賴Jar包
其次烈和,要初步了解SpringBoot解析渲染Thymeleaf的過程
1.整合Thymeleaf需要用到模塊依賴Jar包:Web模塊和Thymeleaf模塊相應(yīng)的依賴Jar包
<dependencies>
<!--thymeleaf模塊依賴-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!--Web模塊依賴-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
上面的依賴在SpringBoot Initializer中勾選Web模塊勾選Web,Themeleaf模塊勾選Thymeleaf
2.構(gòu)建整合Thymeleaf的目錄結(jié)構(gòu)
文件夾 | 說明 |
---|---|
controller | 在Application所在的包下建controller會被SpringBoot自動掃描配置Bean |
static | static是SpringBoot默認加載像CSS,JS,IMG等靜態(tài)資源的文件夾 |
templates | templates默認是放置模板文件皿淋,用來展示渲染的頁面 |
3.controller的代碼內(nèi)容
@Controller告知SpringBoot這是控制層招刹,自動注入Bean
@RequestMapping是映射訪問路徑注解,在localhost:8080之后的路徑就是根據(jù)此處寫的
package com.luojay.springbootthymeleaf.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class ThymeleafController {
@RequestMapping("/getThymeleaf")
public String Welcome(){
return "luojay";
//此處返回值窝趣,對應(yīng)templates的文件名疯暑,SpringBoot根據(jù)它找到對應(yīng)Html
}
}
4.luojay.html代碼內(nèi)容
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>luojay's Thymeleaf</title>
</head>
<body>
hello,luojay!
</body>
</html>
頁面展示效果
進階的學(xué)習(xí)案例
上面的入門例子可以說是簡單到不行,有了這個基礎(chǔ)哑舒,可以利用網(wǎng)上一些靜態(tài)資源整合Thymeleaf搭建好看的頁面,比如登錄界面
文章配套代碼
Github:springboot-thymeleaf
登錄頁面源代碼:基于Layui簡約登錄界面
如果代碼對你有用妇拯,歡迎給個Starts支持一下!