七、Spring Boot 集成 Thymeleaf 模板引擎

前言:上一节对 SpringBoot 的Spring Boot 集成 Swagger2 展现在线接口文档 做了一个介绍,本节主要对Spring Boot 集成 Thymeleaf 模板引擎讲解和分析。

1. Thymeleaf 介绍

Thymeleaf 是适用于 Web 和独立环境的现代服务器端 Java 模板引擎。

Thymeleaf 的主要目标是为您的开发工作流程带来优雅的自然 模板 - 可以在浏览器中正确显示的 HTML,也可以用作静态原 型,从而在开发团队中实现更强大的协作。

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

什么意思呢?就是说在本地环境或者有网络的环境下,Thymeleaf 均可运行。由于 thymeleaf 支持 html 原型,也支持在 html 标签里增加额外的属性来达到 “模板+数据” 的展示方式,所以美工可以直接在浏览器中查看页面效果,当服务启动后,也可以让后 台开发人员查看带数据的动态页面效果。比如:

<div class="ui right aligned basic segment">
	<div class="ui orange basic label" th:text="${blog.flag}">静态原创信息</div>
</div>
<h2 class="ui center aligned header" th:text="${blog.title}">这是 静态标题</h2>

类似与上面这样,在静态页面时,会展示静态信息,当服务启动后,动态获取数据库中 的数据后,就可以展示动态数据,th:text 标签是用来动态替换文本的,这会在下文 说明。该例子说明浏览器解释 html 时会忽略 html 中未定义的标签属性(比如 th:text),所以 thymeleaf 的模板可以静态地运行;当有数据返回到页面时, Thymeleaf 标签会动态地替换掉静态内容,使页面动态显示数据。

2. 依赖导入

Spring Boot 中使用 thymeleaf 模板需要引入依赖,可以在创建项目工程时勾选 Thymeleaf,也可以创建之后再手动导入,如下:

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
  • 另外,在 html 页面上如果要使用 thymeleaf 模板,需要在页面标签中引入:

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

3. Thymeleaf 相关配置

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

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

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

4. Thymeleaf 的使用

4.1 访问静态页面

这个和 Thymeleaf 没啥关系,应该说是通用的,我把它一并写到这里的原因是一般我 们做网站的时候,都会做一个 404 页面和 500 页面,为了出错时给用户一个友好的展示,而不至于一堆异常信息抛出来。Spring Boot 中会自动识别模板目录(templates/) 下的 404.html500.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 页面

[@Controller](https://my.oschina.net/u/1774615)
@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:8080/thymeleaf/test505 时,会抛出异常,然后会自动跳转到 500.html 显示。

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

4.2 Thymeleaf 中处理对象

我们来看一下 thymeleaf 模板中如何处理对象信息,假如我们在做个人博客的时候,需 要给前端传博主相关信息来展示,那么我们会封装成一个博主对象,比如:

public class Blogger {

	private Long id;
	private String name;
	private String pass;
	//set get ......
}

然后在 controller 层中初始化一下:

@GetMapping("/getBlogger")
public String getBlogger(Model model) {
	Blogger blogger = new Blogger(1L, "理性思考", "123456");
	model.addAttribute("blogger", blogger);
	return "blogger";
}

我们先初始化一个 Blogger 对象,然后将该对象放到 Model 中,然后返回到 blogger.html 页面去渲染。接下来我们再写一个 blogger.html 来渲染 blogger 信息:

<!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="${blogger}" >
	用户编号:<input name="id" th:value="${blogger.id}"/><br>
	用户姓名:<input type="text" name="username" th:value="${blogger.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/getBlogger 来测试一下数据:

4.3 Thymeleaf 中处理 List

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

	@GetMapping("/getList")
	public String getList(Model model) {
		Blogger blogger1 = new Blogger(1L, "理性思考", "123456");
		Blogger blogger2 = new Blogger(2L, "感同身受", "123456");

		List<Blogger> list = new ArrayList<>();
		list.add(blogger1);
		list.add(blogger2);
		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="blogger : ${list}" >
	用户编号:<input name="id" th:value="${blogger.id}"/><br>
	用户姓名:<input type="text" name="password" th:value="${blogger.name}"/><br>
	登录密码:<input type="text" name="username" th:value="${blogger.getPass()}"/>
</form>
</body>
</html>

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

4.4 其他常用 thymeleaf 操作

我们来总结一下 thymeleaf 中的一些常用的标签操作

Thymeleaf 还有很多其他用法,这里就不总结了,具体的可以参考 Thymeleaf官方文档(v3.0)。主要要学会如何在 Spring Boot 中去使用 thymeleaf,遇到对应的标签或 者方法,查阅官方文档即可。

5. 总结

ThymeleafSpring Boot 中使用非常广泛,本节课主要分析了 thymeleaf 的优点,以 及如何在 Spring Boot 中集成并使用 thymeleaf 模板,包括依赖、配置,相关数据的获 取、以及一些注意事项等等。最后列举了一些 thymeleaf 中常用的标签,在实际项目中 多使用,多查阅就能熟练掌握,thymeleaf 中的一些标签或者方法不用死记硬背,用到 什么去查阅什么,关键是要会在 Spring Boot 中集成,用的多了就熟能生巧。


希望可以继续关注后续更新文章! 对自己的技术能力有明确的目标!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章