-
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";
}
}