目录
Thymeleaf 是SpringBoot 推荐的模板引擎 (不推荐Jsp);下面我们将对Thymeleaf 进行装配;
第一步:引入依赖
<!--thymeleaf -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring5</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-java8time</artifactId>
</dependency>
第二步,创建模板
注意:模板的默认目录是在templates下
<!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>
<!-- 从controller 中取值 替换原有数据 -->
<p th:text="${welcome}">hello thymeleaf</p>
</body>
</html>
第三步:数据处理
在controller中处理数据:
package com.cjr.demo.controller;
import java.util.Map;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class helloWorld {
@RequestMapping("/welcome")
public String welcome(Map<String,Object> map) {
map.put("welcome", "welcomeThymeleaf"); // requst域中放入值
return "result";//返回到result.html 中
}
}
结果
SpringBoot 整合Thymeleaf 相对比较方便,但是Thymeleaf的语法还需要多多熟悉。