一、前言
前端交给我们的页面,是html页面。如果是我们以前开发,我们需要把他们转成jsp页面,jsp好处就是当我们查出一些数据转发到JSP页面以后,我们可以用jsp轻松实现数据的显示,及交互等。jsp支持非常强大的功能,包括能写Java代码,但是呢,我们现在的这种情况,SpringBoot这个项目首先是以jar的方式,不是war, 第二,我们用的还是嵌入式的Tomcat,所以呢,他现在默认是不支持jsp的。
那不支持jsp,如果我们直接用纯静态页面的方式,那给我们开发会带来非常大的麻烦,那怎么办呢,SpringBoot推荐你可以来使用模板引擎。那么这模板引擎,其实jsp就是一个模板引擎,还有以用的比较多的freemarker,包括SpringBoot给我们推荐的Thymeleaf,模板引擎有非常多,但再多的模板引擎,他们的思想都是一样的。
模板引擎的作用就是我们来写一个页面模板, 比如有些值呢,是动态的,我们写一些表达式。而这些值,从哪来呢,我们来组装一些数据 ,我们把这些数据找到。然后把这个模板和这个数据交给我们模板引擎,模板引擎按照我们这个数据帮你把这表达式解析、填充到我们指定的位置,然后把这个数据最终生成个我们想要的内容给我们写出去, 这就是我们这 个模板引擎,不管是jsp还是其他模板弓引|擎,都是这个思想。
二、引用
Thymeleaf官网
Thymeleaf在Github的主页
Spring官方文档
2.1、导入相关依赖
<!-- 使用thymeleaf模板引擎基于3.x开发,需要导入的依赖-->
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-java8time</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring5</artifactId>
</dependency>
Maven会自动下载jar包
三、测试
3.1、Thymeleaf自动装配类ThymeleafProperties
3.2、编写测试类HelloController
package com.massimo.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
//在templates目录下的所有页面,只能通过controller来跳转
//这个需要模板引擎支持
@Controller
public class HelloController {
@RequestMapping("/test")
public String hello(Model model){
model.addAttribute("msg","hello,springboot");
return "test";
}
}
3.3、在templates下编写test.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<!--/*@thymesVar id="msg" type="resource"*/-->
<div th:text="${msg}"></div>
</body>
</html>