在之前的web项目中,我们的前端页面是用Jsp写的,但SpringBoot默认不支持Jsp,它推荐我们使用Thymeleaf模板引擎
和Jsp一样,我们可以写一个Thymeleaf页面模板,在模板里写上表达式,模板引擎就会通过这个模板和后台封装的数据把这表达式解析、填充到我们指定的位置,最后将数据展示出来
引入Thymeleaf的场景启动器
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
点进去发现这个启动器导入了下面几个依赖
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<version>2.6.2</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring5</artifactId>
<version>3.0.14.RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-java8time</artifactId>
<version>3.0.4.RELEASE</version>
<scope>compile</scope>
</dependency>
</dependencies>
我们来看一下Thymeleaf的自动配置规则,找到ThymeleafProperties,看到默认的前缀和后缀
public static final String DEFAULT_PREFIX = "classpath:/templates/";
public static final String DEFAULT_SUFFIX = ".html";
我们只需要把html页面放在类路径下的templates下,Thymeleaf就可以帮我们自动渲染了
TestController
@Controller
public class TestController {
@RequestMapping("/t1")
public String test1(Model model){
model.addAttribute("msg","Hello SpringBoot");
return "test";
}
}
test.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div th:text="${msg}"></div>
</body>
</html>
关于Thymeleaf语法的学习还是要参考官方文档