添加 Thymeleaf 依赖有两种方式:
Templeate Engines
中勾选 Thymeleaf;pom.xml
中手动添加依赖即可;<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
User
package com.cunyu.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.stereotype.Component;
/**
* @author : cunyu
* @version : 1.0
* @className : Author
* @date : 2020/7/29 16:20
* @description : User 实体类
*/
@Component
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private int age;
private String name;
private String email;
}
package com.cunyu.controller;
import com.cunyu.pojo.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
/**
* @author : cunyu
* @version : 1.0
* @className : UserController
* @date : 2020/7/29 16:22
* @description : UserController
*/
@Controller
public class UserController {
// 访问 ip:port/index
@GetMapping("/index")
public ModelAndView index() {
ModelAndView modelAndView = new ModelAndView();
// 设置跳转的视图
modelAndView.setViewName("index");
modelAndView.addObject("title", "Thymeleaf 使用");
modelAndView.addObject("desc", "Spring Boot 整合 Thymeleaf");
User author = new User(25, "村雨遥", "747731461@qq.com");
modelAndView.addObject("author", author);
return modelAndView;
}
}
第 2.3 中,设置了跳转的视图为 index
,所以我们需要在 src/main/resources/templates
中创建 index.html
;
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title th:text="${title}"></title>
</head>
<body>
<h1 th:text="${desc}" th:align="center"></h1>
<h2 th:align="center">=====作者信息=====</h2>
<p th:text="${author?.name}"></p>
<p th:text="${author?.age}"></p>
<p th:text="${author?.email}"></p>
</body>
</html>
启动项目,然后在浏览器中访问 http://localhost:8080/index
,如果出现下图中的信息,说明整合成功。
为了方便使用,我们在使用 Thymeleaf 模板时,可以添加一些自己的配置;
# thymelea模板配置
# 设置模板文件存放位置
spring.thymeleaf.prefix=classpath:/templates/
# 设置模板后缀
spring.thymeleaf.suffix=.html
# 语法严格限制
spring.thymeleaf.mode=HTML5
# 编码格式
spring.thymeleaf.encoding=UTF-8
# 热部署,每次修改静态页面都不用重启就可以生效,默认为 true
spring.thymeleaf.cache=false
[1]Tutorial: Using Thymeleaf: https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html
[2]Tutorial: Thymeleaf + Spring: https://www.thymeleaf.org/doc/tutorials/3.0/thymeleafspring.html