SpringBoot - 整合Thymeleaf模板引擎(附样例)
作者:hangge | 2019-09-02 08:10
一、基本介绍
1,什么是 Thymeleaf
- Thymeleaf 是新一代的 Java 模版引擎,类似于 Velocity、FreeMarker 等传统 Java 模版引擎。
- Thymeleaf 的主要目标是将优雅的自然模板带到开发工作流程中,并将 HTML 在浏览器中正确显示,并且可以作为静态原型,让开发团队能更容易地协作。Thymeleaf 能够处理 HTML、XML、JavaScript、CSS 甚至纯文本。
- Thymeleaf 也是 Spring Boot 官方推荐使用的模版引擎。同时 Spring Boot 也为 Thymeleaf 提供了完整的自动化配置解决方案。
2,常用的语法
(1)常用表达式
- ${...}:变量表达式。
- *{...}:选择表达式。
- #{...}:消息文字表达式。
- @{...}:链接 url 表达式。
- #maps:工具对象表达式。
(2)常用标签
- 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:属性赋值。
(3)常用函数
- #dates:日期函数。
- #lists:列表函数。
- #arrays:数组函数。
- #strings:字符串函数。
- #numbers:数字函数。
- #calendars:日历函数。
- #objects:对象函数。
- #bools:逻辑函数。
3,安装配置
(1)Spring Boot 工程如果要使用 Thymeleaf,只需编辑 pom.xml 文件,添加 spring-boot-starter-web 和 spring-boot-starter-thymeleaf 依赖即可。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
(2)如果我们需要对默认的 Thymeleaf 配置参数进行自定义,可以直接在 application.properties 中进行配置。下面是一些常见的配置:
#是否开启缓存,开发时可以设置为 false,默认为 true spring.thymeleaf.cache=true #检查模版是否存在,默认为 true spring.thymeleaf.check-template=true #检查模版位置是否存在,默认为 true spring.thymeleaf.check-template-location=true #模版文件编码 spring.thymeleaf.encoding=UTF-8 #模版文件位置 spring.thymeleaf.prefix=classpath:/templates/ #Content-Type配置 spring.thymeleaf.servlet.content-type=text/html #模版文件后缀 spring.thymeleaf.suffix=.html
二、使用样例
1,配置控制器
(1)首先我们定义一个 Book 类:
@Setter
@Getter
@AllArgsConstructor
public class Book {
private Integer id;
private String name;
private String author;
}
(2)然后在 Controller 中创建 Book 实体类,并返回 ModelAndView。
@RestController
public class HelloController {
@GetMapping("/test")
public ModelAndView test() {
// 创建返回数据
List<Book> books = new ArrayList<>();
Book b1 = new Book(1, "hangge.com", "hangge");
Book b2 = new Book(2, "航歌", "hangge");
books.add(b1);
books.add(b2);
// 创建并返回 ModelAndView
ModelAndView mv = new ModelAndView();
mv.addObject("books", books); // 设置返回的数据
mv.setViewName("index"); //设置视图名
return mv;
}
}
2,创建视图
在 resource/templates 目录下创建 index.html,页面中通过遍历将 books 中的数据展示出来。内容如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<table border="1">
<tr>
<td>编号</td>
<td>名称</td>
<td>作者</td>
</tr>
<tr th:each="book:${books}">
<td th:text="${book.id}"></td>
<td th:text="${book.name}"></td>
<td th:text="${book.author}"></td>
</tr>
</table>
</body>
</html>
3,测试运行
在浏览器中访问 http://localhost:8080/test,可以看到运行结果如下:
全部评论(0)