1. 在pom.xml文件引入thymeleaf的依赖。
<!-- 与Thymeleaf集成 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2.在application.properties(application.yml)文件中配置thymeleaf。
# thymeleaf
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.check-template-location=true
spring.thymeleaf.suffix=.html
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.content-type=text/html
spring.thymeleaf.mode=HTML5
spring.thymeleaf.cache=false
spring.resources.chain.strategy.content.enabled=false
spring.resources.chain.strategy.content.paths=
3.新建编辑控制层代码ThymeleafController,在里面设置返回的html路径和设置返回的参数。
package com.example.demo.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class ThymeleafController {
@RequestMapping("/hello")
public ModelAndView hello(ModelAndView mv){
mv.setViewName("/welcome");
mv.addObject("title","欢迎使用Thymeleaf!");
return mv;
}
}
当然也可以不使用ModelAndView,也可以使用Model。
@RequestMapping("hello2")
public String hello2(Model model){
model.addAttribute("title","第二个");
return "welcome";
}
4.新建编辑模板文件,在resources文件夹下的templates目录,用于存放HTML等模板文件,在这新增welcome.html,添加如下代码。
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8"/>
<title>springboot-thymeleaf demo</title>
</head>
<body>
<p th:text="'hello, ' + ${title} + '!'" />
</body>
</html>
6.Warning:使用Thymeleaf模板引擎时,必须在html文件上方添加该行代码使用支持Thymeleaf。
<html lang="en" xmlns:th="http://www.thymeleaf.org">