动态

详情 返回 返回

Thymeleaf的使用 - 动态 详情

前言

由於釘釘機器人發送Markdown消息 手機部不支持table格式顯示(pc端支持table格式顯示),打算使用thymeleaf顯示信息。因為thymeleaf是 Spring boot推薦的引擎模版,站在巨人的肩膀上!如果您有更好的推薦,先謝謝您!

image.pngimage.png

什麼是thymeleaf

在官網中有這麼一條介紹:

Thymeleaf is a modern server-side Java template engine for both web and standalone environments.

直譯過來是:Thymeleaf是一個現代的服務器端Java模板引擎,適用於web和獨立環境

模版引擎

Web 開發中的模板引擎是一種工具,用於將動態數據與預定義的 HTML 或其他頁面模板結合,生成最終的網頁內容。這些模板引擎允許開發者在服務器端或客户端創建動態網頁,而不用手動拼接 HTML 字符串。

比如,我們收到的錄取通知書,就是一個固定的模板,只有姓名、學院、專業是動態的,其餘的都是靜態的。

動靜分離

圖中紅線箭頭是動態訪問,步驟如下:

  • 訪問相應的地址:/dispatch/index
  • Model 是 Spring MVC 中的一個接口,用來在控制器中處理數據,並將數據傳遞給視圖層,
  • 將名為 "name"、"age" 的屬性分別設置為 "張三"、“20”。
  • 把數據傳入給,“index.html” 模版中。
  • 網絡訪問的時候,會去尋找th:text標籤進行替換。
  • 最終顯示:張三、20

綠色箭頭是靜態訪問:步驟如下:

  • 在resources目錄下啓動了http-server。
  • 在瀏覽器中訪問(.../temolates/index.html),看到th:text標籤 “我”不認識,但是不影響我顯示。
  • 最終顯示:李四(我是離線數據)、8(我是離線數據)。

image.png

簡單實用

引入

在pom.xml中添加以下依賴:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

在application文件中添加配置

如圖:
image.png

配置內容如下:
image.png

默認thymeleaf.cache是為true的。表示會啓用模板緩存,為了在開發中出現一些沒必要的麻煩,設置為:false,禁用緩存,在每次啓動請求時,都會重新解析和加載模板。

創建對象

為了更好的顯示,創建一個對象

public class Student {
    String name;
    List<String> courses;

    public Student(String name, List<String> courses) {
        this.name = name;
        this.courses = courses;
    }

    public List<String> getCourses() {
        return courses;
    }

    public void setCourses(List<String> courses) {
        this.courses = courses;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

創建Controller

  • @Controller: 標識這個類是一個控制器(Controller)。
  • @RequestMapping("dispatch"): 一個類級別的註解,指定該控制器處理的基礎 URL。
  • @GetMapping("students"):處理GET請求,並映射到 /dispatch/students URL。
  • Model 對象用於在控制器和視圖之間傳遞數據。

@Controller
@RequestMapping("dispatch")
public class DispatchController {
    @GetMapping("students")
    public String getStudents(Model model) {
        List<Student> students = new ArrayList<>();
        students.add(new Student("張三", Arrays.asList("數學", "英語", "物理")));
        students.add(new Student("李四", Arrays.asList("化學", "生物", "歷史")));
        students.add(new Student("王五", Arrays.asList("地理", "政治", "語文")));

        // 將數據添加到模型中
        model.addAttribute("students", students);
        return "students";
    }
}

創建模版

需要在resources文件下創建templates文件夾,在templates文件夾中創建模版,因為項目啓動的時候會先默認的在resources -〉templates 下尋找模版。如圖:

image.png

students.html 模版

xmlns:th="http://www.thymeleaf.org" 必須攜帶。它告訴瀏覽器和 Thymeleaf 模板引擎,任何帶有 th: 前綴的屬性(如 th:text、th:each 等)都是 Thymeleaf 特定的屬性,而不是標準的 HTML 屬性。

  • th:each,用於循環遍歷集合或數組。
  • th:text,用來動態設置元素文本內容的屬性。
  • ${...} 變量表達式,用於動態獲取和顯示控制器傳遞到視圖中的變量。
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>學生列表</title>
</head>
<body>
<h1>學生列表</h1>
<table border="1">
    <thead>
    <tr>
        <th>姓名</th>
        <th>課程</th>
    </tr>
    </thead>
    <tbody>
<tr th:each="student : ${students}">
    <td th:text="${student.name}"></td>
    <td>
        <ul>
            <li th:each="course : ${student.courses}" th:text="${course}"></li>
        </ul>
    </td>
</tr>
    </tbody>
</table>
</body>
</html>

最終效果

當後台啓動後:訪問:http://localhost:8080/dispatch/students,會得到如下效果:

image.png

遇到的問題

@Controller 和 @RestController

使用@RestController 作為控制器,當訪問 http://localhost:8080/dispatch/students,返回的事一個字符串,而不是我對應的模板。
image.png

image.png

使用@Controller,才是返回的模板信息。

Controller

用於定義一個普通的 Spring MVC 控制器。這個控制器通常用於返回視圖(HTML 頁面),比如我們前面的模板。

@RestController

是 @Controller 和 @ResponseBody 的組合註解。用於定義一個 RESTful 控制器,返回的結果直接是數據(通常是 JSON 或 XML),而不是視圖模板。

所以:

  • 返回 HTML 頁面或視圖的 Web 應用程序,使用 @Controller
  • 返回 JSON 或 XML 數據的 RESTful API,使用 @RestController

總結

由於當前功能只需要這些知識內容。目前先學到這,等後面在需要,繼續學習。
上面只是Thymelea的冰山一角,如果你想學習更多內容,請前往官網。

參考

https://www.thymeleaf.org/
https://developer.aliyun.com/article/769977#comment

user avatar alibabawenyujishu 头像 jianxiangjie3rkv9 头像 fengyan_60cea4fbda03d 头像 solvep 头像 niuqh 头像 lslove 头像 dunizb 头像 febobo 头像 munergs 头像 usdoc 头像 DingyLand 头像 lovecola 头像
点赞 29 用户, 点赞了这篇动态!
点赞

Add a new 评论

Some HTML is okay.