Thymeleaf作为spring官方推荐的模板引擎,在spring体系中使用异常方便。这里以gradle构建的项目为例来说明。
首先,你要先修改build.gradle引入Springboot对Thymeleaf提供的依赖包。在dependencies中增加如下配置。
compile('org.springframework.boot:spring-boot-starter-thymeleaf')
等待gradle帮你自己下载完依赖包后,你可以看到引入的Thymeleaf的版本。
嗯?springboot1.5.7默认引用的Thymeleaf依赖包居然还是2.1.5版本。最新的Thymeleaf不是已经更新3.x版本了么。如果我想使用最新版的Thymeleaf要怎么办呢。
在build.gradle文件中,buildscript下增加配置,完整的配置如下图
ext['thymeleaf.version'] = '3.0.7.RELEASE'
ext['thymeleaf-layout-dialect.version'] = '2.2.2'
等待gradle下载完成,你可以看到引入的Thymeleaf已经是最新版本了。
快速入门
接下来要在项目中使用Thymeleaf了,这里用一个简单的单表查询来举个栗子。
一般来说,开发一个需要渲染数据的页面,分为三个步骤。
1.开发静态页面,即常说的模型。
2.获取数据。
3.使用数据对静态页面进行渲染。
这里我们先做第一个步骤,开发静态页面。为了简单,就不做任何css了,下面是页面的源码。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>标题</title>
</head>
<body>
<strong>标题</strong>
<form action="list.html" method="post">
<input type="hidden" name="pageNumber">
用户名:<input type="text" name="username">
<br/>
姓名:<input type="text" name="name">
<br/>
<button type="submit">提交</button> <button type="reset">重置</button>
</form>
<table>
<thead>
<tr>
<th class="am-hide-sm-only">id</th>
<th>用户名</th>
<th>姓名</th>
<th class="am-hide-sm-only">电话</th>
<th class="am-hide-sm-only">邮箱</th>
<th class="am-hide-sm-only">是否可用</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr>
<td>id</td>
<td>用户名&l