Java學習之Thymeleaf使用
0x00 前言
為了后續的代碼審計一些常用的框架和技術都是有必要了解一下,在此重拾Spring Boot等開發知識內容。
0x01 Thymeleaf簡介
Thymeleaf是一個現代的服務器端Java模板引擎的web和獨立的環境,能夠處理HTML, XML, JavaScript, CSS,甚至純文本。
Thymeleaf的主要目標是提供一種優雅的和高度可維護的方式來創建模板。為了實現這一點,它構建在自然模板的概念上,以不影響模板作為設計原型使用的方式將其邏輯注入模板文件。這改進了設計的交流,並在設計和開發團隊之間架起了橋梁。
Thymeleaf的設計從一開始就考慮了Web標准,尤其是HTML5
Thymeleaf是一個非常可擴展的模板引擎(事實上它可以被稱為模板引擎框架),它允許你定義和自定義的方式,你的模板將被處理到一個精細的細節級別。
將一些邏輯應用到標記工件(標記、一些文本、注釋,如果模板不是標記,則僅僅是占位符)的對象稱為處理程序,這些處理程序的集合—加上一些額外的工件—通常是方言的組成部分。Thymeleaf的核心庫提供了一種稱為標准方言的方言,這對大多數用戶來說應該足夠了。
0x02 Thymeleaf 基礎配置
這里主要以Srping Boot為主
<!--引入thymeleaf依賴-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
在項目的resources\templates
目錄下創建HTML文件,這里注意導入thymeleaf的命名空間,否則無法進行模板的渲染。
<!doctype html>
<!--注意:引入thymeleaf的名稱空間-->
<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>Document</title>
</head>
<body>
<p th:text="'hello SpringBoot'">hello thymeleaf</p>
</body>
</html>
編寫Controller
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class IndexController {
@GetMapping("home")
public String index() {
return "index";
}
}
這里的注解需要使用@Controller
,不能使用@RestController
注解,否則會報錯.
-
如果只是使用@RestController注解Controller,則Controller中的方法無法返回jsp頁面,或者html,配置的視圖解析器 InternalResourceViewResolver不起作用,返回的內容就是Return 里的內容。
-
如果需要返回到指定頁面,則需要用 @Controller配合視圖解析器InternalResourceViewResolver才行。
如果需要返回JSON,XML或自定義mediaType內容到頁面,則需要在對應的方法上加上@ResponseBody注解。
0x03 Thymeleaf 語法
類型
- 1.變量表達式
- 2.選擇或星號表達式
- 3.文字國際化表達式
- 4.URL表達式
${...}變量表達式
<span th:text="${book.author.name}">
<li th:each="book : ${books}">
@{...} 鏈接表達式
@{/order/list}
@{/order/details(id=${orderId})}
或者是
<form th:action="@{/createOrder}">
<a href="main.html" th:href="@{/main}">
#{...} 消息表達式
#{main.title}
#{message.entrycreated(${entryId})}
*{...} 選擇變量表達式
<div th:object="${book}">
...
<span th:text="*{title}">...</span>
...
</div>
常用th標簽
th標簽屬性
1)th:text:文本替換;
2)th:utext:支持html的文本替換。
3)th:value:屬性賦值
4)th:each:遍歷循環元素
5)th:if:判斷條件,類似的還有th:unless,th:switch,th:case
6)th:insert:代碼塊引入,類似的還有th:replace,th:include,常用於公共代碼塊提取的場景
7)th:fragment:定義代碼塊,方便被th:insert引用
8)th:object:聲明變量,一般和*{}一起配合使用,達到偷懶的效果。
9)th:attr:設置標簽屬性,多個屬性可以用逗號分隔
0x04 結尾
內容比較簡單,主要作為記錄。