Thymeleaf
springboot 集成 Thymeleaf
示例:D:\java\demo\student\thymeleaf
1. Thymeleaf 介绍
2. 依赖导入
在 Spring Boot 中使用 thymeleaf 模板需要引入依赖,可以在创建项目工程时勾选 Thymeleaf,也可以创建之后再手动导入。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
如果在 html 文件中使用 thymeleaf 模板,则需要在标签中引入 th 命名空间
<html xmlns:th="http://www.thymeleaf.org">
3. Thymeleaf 配置
Thymeleaf 默认是开启页面缓存的,所以在开发的时候,需要关闭这个页面缓存的时候在 application.yml 配置文件中关闭:
spring:
thymeleaf:
cache: false #关闭缓存
如果不关闭缓存,就会导致页面没法及时看到更新后的效果。
比如修改了一个文件,tomcat 已经重新部署了,但刷新页面还是之前的页面,就是因为缓存引起的。
4. Thymeleaf 的使用
4.1 访问静态(错误)页面
制作一个 404 页面和 500 页面,以便出错时给用户一个友好的展示,而不至于一堆异常信息抛出来。
Spring Boot 会自动识别模板目录 templates/ 下的 404.html 和 500.html 文件。
resources/templates/404.html
在 templates/目录下新建一个 error 文件夹,专门放置错误的 html 页面,然后分别打印些信息。
4.2 Controller类的配置
在 Controller 层我们不能使用 @RestController 注解,而应该使用 @Controller 注解。
@RestController 注解,自动会把返回的数据转成 json 格式。但我们在使用 thymeleaf 模板时,返回的是视图文件名。
@Controller
@RequestMapping("/thymeleaf")
public class ThymeleafController {
@RequestMapping("/test500")
public String test500() {
int i = 1 / 0;
return "index";
}
}
比如上面的 Controller 中是返回到 index.html 页面,如果使用@RestController 的话,会把 index 当作 String 解析了,直接返回"index"字符串到页面,而不是去找 index.html 页面,所以在使用模板时要用@Controller 注解。
4.3 Thymeleaf 中处理数据
4.3.1 对象
thymeleaf 模板中应该如何处理对象信息呢?假如在做个人博客的时候,需要给前端传博主相关信息来展示,分为三步:
- 1封装成对象
public class Bloger{
private Long id;
private String name;
private String pass;
}
- 2在 controller 层中初始化:
先初始化一个 Blogger 对象,然后将该对象放到 Model 中,然后返回到 blogger.html 页面去渲染。
@GetMapping("/getBlogger")
public String getBlogger(Model model){
Blogger blogger = new Blogger(1L, "lijunrui","123456");
model.addAttribute("blogger", blogger);
return "blogger";
}
- 3.在 blogger.html 页面中渲染:
<!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="${}"来获取对象信息.
在 from 表单中可以有三种方式来获取对象属性:
- 1、使用 th:value="*{属性名}"
- 2、使用 th:value="${对象.属性名}",对象指的是上面使用 th:object 获取的对象
- 3、使用 th:value="${对象.get 方法}",对象指的是上面使用 th:object 获取的对象
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?