- 内容简介
- 前言
- 第 1 章 第一个 Spring Boot 项目
- 第 2 章 集成 MySQL 数据库
- 第 3 章 集成 Spring Data JPA
- 第 4 章 使用 Thymeleaf 模板引擎
- 第 5 章 Spring Boot 事务支持
- 第 6 章 使用过滤器和监听器
- 第 7 章 集成 Redis 缓存
- 第 8 章 集成 Log4j 日志
- 8.3 使用 Log4j 记录日志
- 第 9 章 Quartz 定时器和发送 Email
- 第 10 章 集成 MyBatis
- 第 11 章 异步消息与异步调用
- 第 12 章 全局异常处理与 Retry 重试
- 第 13 章 集成 MongoDB 数据库
- 第 14 章 集成 Spring Security
- 第 15 章 Spring Boot 应用监控
- 第 16 章 集成 Dubbo 和 Zookeeper
- 第 17 章 多环境配置与部署
- 第 18 章 Spring Boot 原理解析
- 参考文献
文章来源于网络收集而来,版权归原创者所有,如有侵权请及时联系!
4.2 使用 Thymeleaf 模板引擎

4.2.1 引入依赖
要使用 Thymeleaf 模板引擎,我们需要在 pom.xml 文件中引入依赖。依赖引入之后,记得刷新依赖。具体代码如下:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
同时,我们还需要在 application.properties 文件中添加 Thymeleaf 配置,具体代码如下:
#thymeleaf 配置 # 模板的模式,支持 HTML、XML、TEXT、JAVASCRIPT 等 spring.thymeleaf.mode=HTML5 # 编码,可不用配置 spring.thymeleaf.encoding=UTF-8 # 内容类别,可不用配置 spring.thymeleaf.content-type=text/html # 开发配置为 false,避免修改模板还要重启服务器 spring.thymeleaf.cache=false # 配置模板路径,默认是 templates,可以不用配置 #spring.thymeleaf.prefix=classpath:/templates/
这里要注意的是,Thymeleaf 模板引擎默认会读取 my-spring-boot 项目资源文件夹 resource 下的 templates 目录,这个目录是用来存放 HTML 文件的。如果我们添加了 Thymeleaf 依赖,而没有进行任何配置,或者添加默认目录,启动应用时就会报错。
4.2.2 控制层开发
在 my-spring-boot 项目目录/src/main/java/com.example.demo.controller 下开发控制层类 AyUserController.java,同时把 AyUserService 服务注入控制层类当中。具体代码如下:
- @Controller:标注此类为一个控制层类,同时让 Spring Boot 容器管理起来。
- @RequestMapping:是一个用来处理请求地址映射的注解,可用于类或者方法。用于类,表示类中所有响应请求的方法都是以该地址作为父路径的。@RequestMapping 注解有 value、method 等属性,value 属性可以默认不写。“/ ayUser”就是 value 属性的值。value 属性的值就是请求的实际地址。
- Model 对象:一个接口,我们可以把数据库查询出来的数据设置到该类中,前端会从该对象获取数据。其实现类为 ExtendedModelMap,具体可看源代码:
4.2.3 Thymeleaf 模板页面开发
控制层类 AyUserController.java 开发完成之后,我们继续在/src/main/resources/ templates 目录下开发 ayUser.html 页面,具体代码如下:
<html xmlns:th="http://www.thymeleaf.org">是 Thymeleaf 命名空间,通过引入该命名空间就可以在 HTML 文件中使用 Thymeleaf 标签语言,用关键字“th”来标注。下面看几个简单的例子:
//th:text 用于显示文本 Hello、Thymeleaf <p th:text=" 'Hello,Thymeleaf' "></p> //${} 关键字用于获取内存变量为 name 的值 <p th:text="${name}"></p> //th:src 用于设定<img> 图片文件的链接地址,@{} 为超链接 url 表达式 <img th:src="@{/image/a.jpg}"/>
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论