1、不想看系列
thymeleaf 是一种模板引擎,所谓引擎就是将动态的数据放入静态的html界面,然后渲染出一个新的html页面。
其实jsp就是一种模板引擎,但是和thymeleaf不一样的是,前端写好的html,需要先转成jsp格式,然后再内嵌使用Java代码,用过的同志就知道,Java代码和html标签杂乱不堪,所以过时也是因为这个原因,那thymeleaf就不一样了么?
确实不一样,它和vue有异曲同工之妙,将标签绑定,放入固定的数据,然后渲染出来,前端的html页面你甚至拿来即用,里面你看不到Java代码,它的职责很明确,他就是接到数据渲染页面的。
但是体会过前后端分离的我,还是觉得分离真香。
2、hello thymeleaf
2.1 引入依赖
按照springboot的习惯,我们只需要引入一个starter就好了
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
它会默认帮我们导入
所以其实不用导starter,导那两个依赖也是等价的
2.2 创建hello.html
在哪创建呢?根据前面的文章,spring boot的自动装配原理,我们全局搜索ThymeleafProperties
所以我们需要在classpath:/templates/
目录中创建.html
结尾的文件,这是默认的,也就是说可以修改的,修改就不必多言了。
spring:
thymeleaf:
prefix: classpath:/butcher/
suffix: .jsp
就可以修改它为classpath:/butcher/
目录中创建.jsp
结尾的文件。
好,话多了,我们创建一个hello.hrml文件
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>hello</title>
</head>
<body>
<h1 th:text="${msg}"></h1>
</body>
</html>
根据官网,你要在html中使用thymeleaf,你需要在html标签那加一个命名空间
xmlns:th="http://www.thymeleaf.org"
th:text="${msg}"
取出我们传过来的模板数据
2.3 编写controller
package cn.butcher.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class HelloController {
@GetMapping("/hello")
public String sayHello(Model model){
model.addAttribute("msg","hello thymeleaf!");
return "hello";
}
}
启动!访问/hello
请求