-
Thymeleaf 存放規則
-
前綴路徑classpath:/templates/
-
后綴: .html
-
SpringBoot默認前綴和后綴就是 thymeleaf
-
也就是說把 html 頁面放在resources/templates/ ,thymeleaf 就能自動渲染
<!-- 引入thymeleaf依賴 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<properties>
<thymeleaf.version>3.0.2.RELEASE</thymeleaf.version>
<thymeleaf-layout-dialect.version>2.0.4</thymeleaf-layout-dialect.version>
</properties>
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>
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"; } }