第011课:Spring Boot 集成Thymeleaf模板引擎

682 阅读5分钟

1. Thymeleaf 介绍

Thymeleaf 是适用于 Web 和独立环境的现代服务器端 Java 模板引擎。
Thymeleaf 的主要目标是为您的开发工作流程带来优雅的自然模板 - 可以在浏览器中正确显示的HTML,也可以用作静态原型,从而在开发团队中实现更强大的协作。

Thymeleaf 介绍

以上翻译自 Thymeleaf 官方网站。传统的 JSP+JSTL 组合是已经过去了,Thymeleaf 是现代服务端的模板引擎,与传统的 JSP 不同,Thymeleaf 可以使用浏览器直接打开,因为可以忽略掉拓展属性,相当于打开原生页面,给前端人员也带来一定的便利。

2. 常用语法

常用表达式

${...}:变量表达式。 
*{...}:选择表达式。 
#{...}:消息文字表达式。 
@{...}:链接 url 表达式。 
#maps:工具对象表达式。

常用标签

th:action:定义后台控制器路径。 
th:each:循环语句。 
th:field:表单字段绑定。 
th:href:定义超链接。 
th:id:div 标签中的 ID 声明,类似 HTML 标签中的归属性。 
th:if:条件判断语句。 
th:include:布局标签,替换内容到引入文件。 
th:fragment:布局标签,定义一个代码片段,方便其他地方引用。 
th:object:替换对象。 
th:src:图片类地址引入。 
th:text:显示文本。 
th:value:属性赋值。

常用函数

#dates:日期函数。 
#lists:列表函数。 
#arrays:数组函数。 
#strings:字符串函数。 
#numbers:数字函数。 
#calendars:日历函数。 
#objects:对象函数。 
#bools:逻辑函数。 

例子:thymeleaf 中的一些常用的标签操作,如下:

标签功能例子
th:value给属性赋值<input th:value="${blog.name}" />
th:style设置样式th:style="'display:'+@{(${sitrue}?'none':'inline-block')} + ''"
th:onclick点击事件th:onclick="'getInfo()'"
th:if条件判断<a th:if="${userId == collect.userId}" >
th:href超链接<a th:href="@{/blogger/login}">Login</a> />
th:unless条件判断和th:if相反<a th:href="@{/blogger/login}" th:unless=${session.user != null}>Login</a>
th:switch配合th:case<div th:switch="${user.role}">
th:case配合th:switch<p th:case="'admin'">administator</p>
th:src地址引入<img alt="csdn logo" th:src="@{/img/logo.png}" />
th:action表单提交的地址<form th:action="@{/blogger/update}">

Thymeleaf 还有很多其他用法,这里就不总结了,具体的可以参考Thymeleaf的官方文档(v3.0)

3. 依赖导入

在 Spring Boot 中使用 thymeleaf 模板需要引入依赖,在pom文件中加入以下依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

另外,在 html 页面上如果要使用 thymeleaf 模板,需要在页面标签中引入:

<html xmlns:th="http://www.thymeleaf.org">

4. Thymeleaf相关配置

因为 Thymeleaf 中已经有默认的配置了,我们不需要再对其做过多的配置,有一个需要注意一下,Thymeleaf 默认是开启页面缓存的,所以在开发的时候,需要关闭这个页面缓存,配置如下。

spring:
  thymeleaf:
    cache: false #关闭缓存

否则会有缓存,导致页面没法及时看到更新后的效果。 比如你修改了一个文件,已经 update 到 tomcat 了,但刷新页面还是之前的页面,就是因为缓存引起的。

5. Thymeleaf 的使用

5.1 访问静态页面

我们做网站的时候,都会做一个 404 页面和 500 页面,为了出错时给用户一个友好的展示,而不至于一堆异常信息抛出来。Spring Boot 中会自动识别模板目录(templates/)下的 404.html 和 500.html 文件。我们在 templates/ 目录下新建一个 error 文件夹,专门放置错误的 html 页面,然后分别打印些信息。以 404.html 为例:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
微信公众号【猿码天地】404页面
</body>
</html>

我们再写一个 controller 来测试一下 404 和 500 页面:

package com.bowen.controller;

import com.bowen.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.ArrayList;
import java.util.List;

/**
 * <h3>springboot-study</h3>
 * <p>thymeleaf测试Controller类</p>
 * @author : zhang.bw
 * @date : 2020-07-17 21:37
 **/
@Controller
@RequestMapping("/thymeleaf")
public class ThymeleafController {

    @GetMapping("/test404")
    public String test404() {
        return "index";
    }

    @GetMapping("/test500")
    public String test500() {
        int i = 1 / 0;
        return "index";
    }
}

当我们在浏览器中输入 localhost:8080/thymeleaf/test400 时,故意输入错误,找不到对应的方法,就会跳转到 404.html 显示。

模板引擎

当我们在浏览器中输入 localhost:8088/thymeleaf/test505 时,会抛出异常,然后会自动跳转到 500.html 显示。

模板引擎

注意:这里有个问题需要注意一下,微服务最终会走向前后端分离,我们在 Controller 层上都是使用的 @RestController 注解,自动会把返回的数据转成 json 格式。但是在使用模板引擎时,Controller 层就不能用 @RestController 注解了,因为在使用 thymeleaf 模板时,返回的是视图文件名,比如上面的 Controller 中是返回到 index.html 页面,如果使用 @RestController 的话,会把 index 当作 String 解析了,直接返回到页面了,而不是去找 index.html 页面。所以在使用模板时要用 @Controller 注解。

5.2 Thymeleaf 中处理对象

我们来看一下 thymeleaf 模板中如何处理对象信息,我们定义一个用户信息实体。

public class User {
    private Long id;
    private String name;
    private String pass;
	// 省去set和get
}

然后在controller层获取user信息,并返回给页面。

@GetMapping("/getUser")
public String getUser(Model model) {
    User user = new User(1L, "猿码天地", "公众号猿码天地");
    model.addAttribute("user", user);
    return "user";
}

新建一个user.html页面,用来渲染数据。

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>客户信息</title>
</head>
<body>
<form action="" th:object="${user}" >
    用户编号:<input name="id" th:value="${user.id}"/><br>
    用户姓名:<input type="text" name="username" th:value="${user.getName()}" /><br>
    登陆密码:<input type="text" name="password" th:value="*{pass}" />
</form>
</body>
</html>

可以看出,在 thymeleaf 模板中,使用 th:object="${}" 来获取对象信息,然后在表单里面可以有三种方式来获取对象属性。如下:

使用 th:value="*{属性名}" 使用 th:value="${对象.属性名}",对象指的是上面使用 th:object 获取的对象 使用 th:value="${对象.get方法}",对象指的是上面使用 th:object 获取的对象

可以看出,在 Thymeleaf 中可以像写 java 一样写代码,很方便。我们在浏览器中输入 localhost:8080/thymeleaf/getUser 来测试一下数据:

模板引擎

5.3 Thymeleaf 中处理 List

处理 List 的话,和处理上面介绍的对象差不多,但是需要在 thymeleaf 中进行遍历。我们先在 Controller 中模拟一个 List。

@GetMapping("/getList")
public String getList(Model model) {
    User user1 = new User(1L, "猿码天地1", "公众号猿码天地1");
    User user2 = new User(2L, "猿码天地2", "公众号猿码天地2");

    List<User> list = new ArrayList<>();
    list.add(user1);
    list.add(user2);
    model.addAttribute("list", list);
    return "list";
}

接下来我们写一个 list.html 来获取该 list 信息,然后在 list.html 中遍历这个list。如下:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>客户信息</title>
</head>
<body>
<form action="" th:each="user : ${list}" >
    用户编号:<input name="id" th:value="${user.id}"/><br>
    用户姓名:<input type="text" name="password" th:value="${user.name}"/><br>
    登录密码:<input type="text" name="username" th:value="${user.getPass()}"/>
</form>
</body>
</html>

模板引擎

可以看出,其实和处理单个对象信息差不多,Thymeleaf 使用 th:each 进行遍历,${} 取 model 中传过来的参数,然后自定义 list 中取出来的每个对象,这里定义为 user。表单里面可以直接使用 ${对象.属性名} 来获取 list 中对象的属性值,也可以使用 ${对象.get方法} 来获取,这点和上面处理对象信息是一样的,但是不能使用 *{属性名} 来获取对象中的属性,thymeleaf 模板获取不到。

6. 总结

Thymeleaf 在 Spring Boot 中使用非常广泛,本节课主要讲解了如何在 Spring Boot 中集成并使用 thymeleaf 模板,包括依赖、配置,相关数据的获取、以及一些注意事项等等。同时也列举了一些 thymeleaf 中常用的标签,在实际项目中多使用,多查阅就能熟练掌握。通过本节课程的学习,相信对模板引擎的使用有了更加深刻的认识。

7. 源码获取

我是猿人,分享技术,品位人生,感谢各位点赞、收藏和评论,我们下期见!
文章持续更新,可以微信搜一搜「 猿码天地 」第一时间阅读,回复【springboot】获取完整源码。