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

1. Thymeleaf 介绍

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

Thymeleaf 介绍

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

2. 常用语法

常用表达式

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

常用标签

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

常用函数

1#dates:日期函数。 
2#lists:列表函数。 
3#arrays:数组函数。 
4#strings:字符串函数。 
5#numbers:数字函数。 
6#calendars:日历函数。 
7#objects:对象函数。 
8#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文件中加入以下依赖:

1<dependency>
2    <groupId>org.springframework.boot</groupId>
3    <artifactId>spring-boot-starter-thymeleaf</artifactId>
4</dependency>

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

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

4. Thymeleaf相关配置

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

1spring:
2  thymeleaf:
3    cache: false #关闭缓存

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

5. Thymeleaf 的使用

5.1 访问静态页面

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

 1<!DOCTYPE html>
 2<html lang="en">
 3<head>
 4    <meta charset="UTF-8">
 5    <title>Title</title>
 6</head>
 7<body>
 8微信公众号【猿码天地】404页面
 9</body>
10</html>

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

 1package com.bowen.controller;
 2
 3import com.bowen.entity.User;
 4import org.springframework.stereotype.Controller;
 5import org.springframework.ui.Model;
 6import org.springframework.web.bind.annotation.GetMapping;
 7import org.springframework.web.bind.annotation.RequestMapping;
 8
 9import java.util.ArrayList;
10import java.util.List;
11
12/**
13 * <h3>springboot-study</h3>
14 * <p>thymeleaf测试Controller类</p>
15 * @author : zhang.bw
16 * @date : 2020-07-17 21:37
17 **/
18@Controller
19@RequestMapping("/thymeleaf")
20public class ThymeleafController {
21
22    @GetMapping("/test404")
23    public String test404() {
24        return "index";
25    }
26
27    @GetMapping("/test500")
28    public String test500() {
29        int i = 1 / 0;
30        return "index";
31    }
32}

当我们在浏览器中输入 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 模板中如何处理对象信息,我们定义一个用户信息实体。

1public class User {
2    private Long id;
3    private String name;
4    private String pass;
5    // 省去set和get
6}

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

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

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

 1<!DOCTYPE html>
 2<html xmlns:th="http://www.thymeleaf.org">
 3<html lang="en">
 4<head>
 5    <meta charset="UTF-8">
 6    <title>客户信息</title>
 7</head>
 8<body>
 9<form action="" th:object="${user}" >
10    用户编号:<input name="id" th:value="${user.id}"/><br>
11    用户姓名:<input type="text" name="username" th:value="${user.getName()}" /><br>
12    登陆密码:<input type="text" name="password" th:value="*{pass}" />
13</form>
14</body>
15</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。

 1@GetMapping("/getList")
 2public String getList(Model model) {
 3    User user1 = new User(1L, "猿码天地1", "公众号猿码天地1");
 4    User user2 = new User(2L, "猿码天地2", "公众号猿码天地2");
 5
 6    List<User> list = new ArrayList<>();
 7    list.add(user1);
 8    list.add(user2);
 9    model.addAttribute("list", list);
10    return "list";
11}

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

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

 

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

6. 总结

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

源码下载地址:关注公众号【猿码天地】并回复 springboot 获取

文章推荐

程序员接私活平台,你有技术就有钱!

SpringBoot Utils类注入Bean 详解

MVC,MVP 和 MVVM 图示

滴滴开源项目整理,非常好的实战项目

10年过去了,程序员到底挣了多少钱?

扫描二维码关注公众号 : 猿码天地

你多学一样本事,就少说一句求人的话,现在的努力,是为了以后的不求别人,实力是最强的底气。记住,活着不是靠泪水博得同情,而是靠汗水赢得掌声。

——《写给程序员朋友》

猜你喜欢

转载自blog.csdn.net/zbw125/article/details/107829424