15.0、springboot-Thymeleaf模板引擎
模板引擎将代码和数据渲染后展示到前端页面
模板引擎的作用就是我们来写一个页面模板,比如有些值是动态的,我们写一些表达式。而这些值,从哪来呢,我们来组装一些数据,我们把这些数据找到。然后把这个模板和这个数据交给我们的模板引擎,模板引擎按照我们这个数据帮你把这表达式解析、填充到我们制定的位置,然后把这个数据最终生成一个我们想要的内容给我们写出去,这就是我们这个模板引擎,不管是jsp还是其他模板引擎,都是这个思想。只不过呢,就是说不同模板引擎之间,他们可能语法有点不一样。其他的我就还不介绍了,主要来介绍一下springboot给我们推荐的Thymeleaf模板引擎,折模板引擎是一个高级语言的模板引擎,他的语法更简单,而且功能更加强大。
我们就先来看一下这个模板在springboot里如何使用
第一步:引入thyleaf
到springboot官网https://spring.io/projects/spring-boot
拷贝一份关于thymeleaf的依赖,添加到pom.xml中即可
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring5</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-java8time</artifactId>
</dependency>
这里引入thymeleaf的时候注意要引入3.x以及3.x以上的版本,如果导入的是2.x会直接报错。
以前我们后台传值是jsp现在是thymeleaf
我们先来看看原理原码
先进入ThymeleafProperties.java如下
在template文件夹中创建一个test.html文件,测试成功!如下:
接下来我们来简单测试一个thymeleaf的语法
test.html文件,记得导入相关约束 xmlns:th="http://www.thymeleaf.org"
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>test</title>
</head>
<body>
<h1 th:text="${msg}"></h1>
</body>
</html>
HelloWorld.java文件
package com.hkl.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class HelloController {
@RequestMapping("/test")
public String gototest(Model model) {
model.addAttribute("msg","hello,thymeleaf");
return "test";
}
}
测试成功!