目錄
模板引擎簡介
引入Thymeleaf模板引擎
分析Thymeleaf模板引擎
測驗Thymeleaf模板引擎
Thymeleaf入門:
thymeleaf語法學習
練習測驗
總結:
模板引擎簡介
jsp有著強大的功能,能查出一些資料轉發到JSP頁面以后,我們可以用jsp輕松實作資料的顯示及互動等,包括能寫Java代碼,但是,SpringBoot首先是以jar的方式,不是war;其次我們的tomcat是嵌入式的,所以現在默認不支持jsp,
如果我們直接用純靜態頁面方式,必然會給開發帶來很大麻煩,所以springboot推薦使用模板引擎,其實jsp就是一個模板引擎,還有用的比較多的freemarker,包括SpringBoot給我們推薦的Thymeleaf!模板引擎的本質思想如下圖:

引入Thymeleaf模板引擎
Thymeleaf 官網:Thymeleaf

Spring官方檔案:
https://docs.spring.io/spring-boot/docs/2.2.5.RELEASE/reference/htmlsingle/#using-boot-starter
<!--thymeleaf-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
Maven自動下載jar包,下圖試maven下載的東西;

分析Thymeleaf模板引擎
首先按照SpringBoot的自動配置原理來看一下我們這個Thymeleaf的自動配置規則,再按照這個規則,我們進行使用,可以先去看看Thymeleaf的自動配置類:ThymeleafProperties

我們可以在組態檔看到默認的前綴和后綴!
我們只需要把我們的html頁面放在類路徑下的templates下,thymeleaf就可以幫我們自動渲染,
測驗Thymeleaf模板引擎
1、撰寫一個TestController

2、撰寫一個測驗頁面 test.html 放在 templates 目錄下

3、啟動專案請求測驗

4.結論:只要需要使用thymeleaf,只需要匯入對應的依賴就可以了,然后將html放在templates的目錄下即可
Thymeleaf入門:
我們可以查看下Thymeleaf 官網:https://www.thymeleaf.org/
簡單練習:查出一些資料,在頁面中展示
1、修改測驗請求,增加資料傳輸
@Controller
public class TestController {
@RequestMapping("/t1")
public String test1(Model model){
//存入資料
model.addAttribute("msg","Hello,Thymeleaf");
//classpath:/templates/test.html
return "test";
}
}
2、我們要使用thymeleaf,需要在html檔案中匯入命名空間的約束,方便提示,
xmlns:th="http://www.thymeleaf.org"
3、我們去撰寫下前端頁面
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>九陽真經---龍弟</title>
</head>
<body>
<h1>測驗頁面</h1>
<!--th:text就是將div中的內容設定為它指定的值-->
<div th:text="${msg}"></div>
</body>
</html>
4、啟動測驗!

thymeleaf語法學習
1、使用任意的 th:attr 來替換Html中原生屬性的值!

2.運算式語法:

練習測驗
@Controller
public class TestController {
@RequestMapping("/t2")
public String test2(Map<String,Object> map){
//存入資料
map.put("msg","<h1>Hello,SpringBoot</h1>");
map.put("users", Arrays.asList("dragon","longdi"));
//classpath:/templates/test.html
return "test";
}
}
2、測驗頁面取出資料
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>九陽真經---龍弟</title>
</head>
<body>
<h1>測驗頁面</h1>
<div th:text="${msg}"></div>
<!--不轉義-->
<div th:utext="${msg}"></div>
<!--遍歷資料-->
<!--th:each每次遍歷都會生成當前這個標簽-->
<h4 th:each="user :${users}" th:text="${user}"></h4>
<hr>
<!--行內寫法-->
<h4 th:each="user:${users}">[[${user}]]</h4>
</body>
</html>
3、啟動專案測驗!

總結:
由于thymeleaf很多語法樣式,我們現在學了也會忘記,因此,在學習程序中,需要使用什么,根據官方檔案來查詢,所以要熟練使用官方檔案!
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/305965.html
標籤:java
