Thymeleaf是什么?为什么选择作为模板?
Thymeleaf是SpringBoot提供的一个模板引擎,方便实现前后端数据交互。
SpringBoot提供了大量的模板引擎还包括:
FreeMarker、Velocity、Mustache、Groovy、JSP(内嵌tomcat不友好)
1.Thymeleaf支持html、xml、text、javascript、css、raw几种模型。
2.Thymeleaf 在有网络和无网络的环境下皆可运行,即它可以让美工在浏览器查看页面的静态效果,也可以让程序员在服务器查看带数据的动态页面效果。这是由于它支持 html 原型,然后在 html 标签里增加额外的属性来达到模板+数据的展示方式。浏览器解释 html 时会忽略未定义的标签属性,所以 Thymeleaf 的模板可以静态地运行;当有数据返回到页面时,Thymeleaf 标签会动态地替换掉静态内容,使页面动态显示。
3.Thymeleaf 开箱即用的特性。它提供标准和 Spring 标准两种方言,可以直接套用模板实现 JSTL、 OGNL表达式效果,避免每天套模板、改 Jstl、改标签的困扰。同时开发人员也可以扩展和创建自定义的方言。
4.Thymeleaf 提供 Spring 标准方言和一个与 SpringMVC 完美集成的可选模块,可以快速的实现表单绑定、属性编辑器、国际化等功能。
Thymeleaf官网文档教学:https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#introducing-thymeleaf(3.0)
接下来我们创建SpringBoot(版本2.1.9)项目使用Thymeleaf模板引擎展示数据交互显示页面
1.创建SpringBoot项目,添加maven依赖,项目资源目录如下,static静态资源目录用于存放图片\css\js,templates是SpringBoot的默认模板路径thymeleaf
maven依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
application.properties后缀改成yml格式
#spring配置
spring:
thymeleaf:
mode: HTML5
cache: false
prefix: classpath:/templates/
suffix: .html
encoding: UTF-8
servlet:
content-type: text/html
在templates文件夹下新建index.html目录
index.html
thymeleaf语法参考上面官网文档
要加上xmlns:th="http://www.thymeleaf.org语法声明不然不能使用thymeleaf模板
th:text适用于访问后台传来的数据值
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1 th:text="${info}"></h1>
</body>
</html>
新建controller类
package com.sun.th.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping(value = "/th")
public class ThController {
@RequestMapping(value = "/index")
public String showIndex(Model model){
model.addAttribute("info","这是后台传来的数据");
return "index";
}
}
启动项目,
访问http://localhost:8080/th/index显示信息成功。