Thymeleaf是什么?
模板引擎是为了使前端与后台分离而产生的。模板引擎可以让(网站)程序实现界面与数据分离,业务代码与逻辑代码的分离,这就大大提升了开发效率,良好的设计也使得代码重用变得更加容易。常用的模板引擎有freemarker,thymeleaf,其实jsp也是模板引擎。thymeleaf就是代替之前jsp使用的,SpringBoot这个项目首先是以jar的方式,不是war,所以他现在默认是不支持jsp的。
使用thymeleaf,导入依赖,把html放在templates就可以了。
<!--thymeleaf-->
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring5</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-java8time</artifactId>
</dependency>
Thymeleaf的使用
首先再templates包下新建一个hello.html,在html文件中导入命名空间的约束:xmlns:th="http://www.thymeleaf.org"
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<!--获取msg的值-->
<h3 th:text="${msg}"></h3>
<h3 th:utext="${msg}"></h3>
<hr>
<!--遍历数组的值-->
<h4 th:each="user:${users}" th:text="${user}"></h4>
</body>
</html>
新建一个controller包,在包下新建一个mycontroller类:
package com.lyr.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.Arrays;
@Controller
public class myController {
@RequestMapping("/test")
public String test(Model model){
model.addAttribute("msg","<h3>helloSpringBoot!</h3>");
model.addAttribute("users", Arrays.asList("springBoot","Thymeleaf"));
return "hello";
}
}
然后就可以在hello页面显示msg和数组的内容了