1. 程式人生 > 實用技巧 >7. SpringBoot整合Thymeleaf

7. SpringBoot整合Thymeleaf

  • Thymeleaf存放規則
    • 字首路徑classpath:/templates/
    • 字尾: .html
    • SpringBoot預設字首和字尾就是thymeleaf
    • 也就是說把 html 頁面放在resources/templates/ ,thymeleaf 就能自動渲染

  • Thymeleaf 用法舉例
    • 在pom中引入thymeleaf依賴
<!-- 引入thymeleaf依賴 -->
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
    • 設定thymeleaf版本
<properties>
  <thymeleaf.version>3.0.2.RELEASE</thymeleaf.version>
  <thymeleaf-layout-dialect.version>2.0.4</thymeleaf-layout-dialect.version>
</properties>
    • yml配置檔案設定thymeleaf屬性
spring:
  thymeleaf:
    cache: false
    prefix: classpath:
/templates/ suffix: .html encoding: UTF-8 content-type: text/html mode: HTML5
    • resources/templates/ 中新建 .html 測試檔案
<!DOCTYPE HTML>
<!-- 匯入thymeleaf -->
<html lang="en" xmlns:th="https://www.thymeleaf.org">
<head>
    <title>success</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <!-- th:href = '@{/css/success.css}' 中的css前面的 / 不能省略,會報錯 -->
    <link type='text/css' rel='styleSheet' th:href='@{/css/success.css}'/>
    <!-- 使用單引號和雙引號都行 -->
    <script th:src="@{/js/test.js}"></script>
</head>

<body id="body"> <!-- ${ 讀取name元素存放的內容 } }--> <h2 th:text=" 'Hello, My name is ' + ${name}"></h2> </body>
</html>
    • 編寫Controller類跳轉頁面
package com.asimple.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/thymeleaf")
public class ThymeleafController {
    
    @RequestMapping("/success")
    public String success(Model model) {
        //控制檯驗證是否執行
        System.out.println("This is success of thymeleaf");
        //向前端傳值
        model.addAttribute("name", "XiaoMing");
        //跳轉頁面,由於配置了字首和字尾,相當於是 /templates/success.html
        return "success";
    }
}