Springboot的thymeleaf使用

本文详细介绍了如何在SpringBoot项目中配置并使用Thymeleaf模板引擎,包括视图解析器的设置、依赖包的导入及集合数据的遍历展示,为初学者提供了实用的代码示例。

Springboot的thymeleaf使用

  • thymeleaf包含视图解析器
public static final String DEFAULT_PREFIX = "classpath:/templates/"; // 前缀

public static final String DEFAULT_SUFFIX = ".html";// 后缀

thymeleaf的导包

	<!--thymeleaf基于最新版开发 start-->
    <dependency>
        <groupId>org.thymeleaf</groupId>
        <artifactId>thymeleaf-spring5</artifactId>
    </dependency>
    <dependency>
        <groupId>org.thymeleaf.extras</groupId>
        <artifactId>thymeleaf-extras-java8time</artifactId>
    </dependency>
    <!--thymeleaf end-->

thymeleaf遍历集合

// 第一种方式
<h4 th:each="user:${users}" th:text="${user}"/>
    
// 第二种方式
<h4 th:each="user:${users}">[[ ${user} ]]</h4>
### 如何在 Spring Boot 中集成与使用 Thymeleaf 模板引擎 #### 集成过程概述 Spring Boot 提供了对 Thymeleaf 的开箱即用支持,能够简化其配置并使其与应用程序无缝协作[^3]。以下是关于如何在 Spring Boot 项目中集成和使用 Thymeleaf 的具体说明。 --- #### 添加依赖项 为了使 Thymeleaf 能够正常工作,需在项目的 `pom.xml` 文件中引入相应的 Maven 依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> ``` 此依赖包含了 Thymeleaf 和 Spring Boot 所需的核心库及其默认配置[^1]。 --- #### 创建模板文件 Thymeleaf 默认会在 `src/main/resources/templates/` 目录下查找 HTML 模板文件。如果需要加载静态资源(如 CSS 或 JavaScript),可以将其放置于 `public`, `resources`, 或 `static` 子目录中,这些路径会被 Spring Boot 自动扫描[^2]。 例如,创建一个名为 `index.html` 的模板文件,并存放在上述指定位置: ```html <!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <title th:text="${pageTitle}">Default Title</title> </head> <body> <h1 th:text="${message}">Welcome to the Home Page!</h1> </body> </html> ``` 在此示例中,`${pageTitle}` 和 `${message}` 是占位符变量,它们将在控制器层传递给视图。 --- #### 编写控制器逻辑 通过编写一个简单的 Spring MVC 控制器来渲染 Thymeleaf 模板。以下是一个典型的例子: ```java import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; @Controller public class HomeController { @GetMapping("/") public String home(Model model) { model.addAttribute("pageTitle", "Home Page"); model.addAttribute("message", "Hello from Thymeleaf!"); return "index"; // 返回 templates/index.html } } ``` 在这个控制器方法中,`model.addAttribute()` 方法用于向模型对象添加数据,而返回值 `"index"` 则指定了要使用的模板名称。 --- #### 运行应用 启动 Spring Boot 应用程序后,访问根 URL `/` 就可以看到由 Thymeleaf 渲染后的页面内容。此时,HTML 页面中的动态部分将被替换为实际的数据。 --- #### 特性增强 除了基本功能外,还可以利用 Thymeleaf 的多方言支持特性来自定义表达式语法或扩展标准行为。此外,借助 Spring Boot 的自动配置机制,开发者无需手动设置视图解析器即可完成大部分常见操作。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值