springboot中的thymeleaf


springboot中的thymeleaf


thymeleaf
提取公共部分的代码
在这里插入图片描述

将公用的顶部和侧边的导航栏整合在一块
在这里插入图片描述
格式
th:fragment=“topbar”

~~00000000000000000000000000000000000000000000000000000000 ~~
怎么用
语法 th:insert=~{/commons/commons :: topbar}

在这里插入图片描述

<div th:insert="~{/commons/commons :: topbar}"></div>
### 配置与使用 Thymeleaf 模板引擎 #### 1. Maven 依赖配置 为了在 Spring Boot 项目中使用 Thymeleaf,需确保 `pom.xml` 文件中已引入 Thymeleaf 的 Starter 组件。以下是标准的依赖声明: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> ``` 此依赖会自动集成 Thymeleaf 模板引擎并提供必要的功能支持[^2]。 --- #### 2. 默认配置项 Spring Boot 提供了对 Thymeleaf 的自动装配机制,默认情况下无需额外手动配置即可正常运行。默认参数包括但不限于以下内容: - **模板路径**: `classpath:/templates/` - **编码方式**: UTF-8 - **缓存模式**: 开发环境中禁用缓存以便实时更新模板文件;生产环境启用缓存以提升性能。 如果需要自定义配置,可以在项目的 `application.properties` 或 `application.yml` 文件中调整相关属性。例如: ```properties # application.properties 示例 spring.thymeleaf.prefix=classpath:/custom_templates/ spring.thymeleaf.suffix=.html spring.thymeleaf.cache=false spring.thymeleaf.encoding=UTF-8 ``` 或者通过 YAML 格式实现相同效果: ```yaml # application.yml 示例 spring: thymeleaf: prefix: classpath:/custom_templates/ suffix: .html cache: false encoding: UTF-8 ``` 上述配置允许开发者更改模板存储位置、扩展名以及是否开启缓存等功能[^3]。 --- #### 3. 创建 HTML 页面 创建一个简单的 HTML 文件用于展示数据交互过程。假设我们希望显示一条欢迎消息,则可在 `src/main/resources/templates/` 下新建名为 `index.html` 的文件,其内容如下所示: ```html <!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <title>Welcome Page</title> </head> <body> <h1 th:text="'Welcome to ' + ${appName}"></h1> </body> </html> ``` 在此示例中,`${appName}` 是动态变量,将在控制器层传递给视图渲染逻辑[^4]。 --- #### 4. 控制器代码编写 最后一步是在 Controller 类中返回对应的视图名称,并向模型注入所需的数据对象。下面是一个完整的 Java 实现例子: ```java import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; @Controller public class WelcomeController { @GetMapping("/") public String welcome(Model model) { model.addAttribute("appName", "My Awesome App"); return "index"; // 返回 templates/index.html 对应的视图 } } ``` 当访问根路径 `/` 时,该方法会被触发并将字符串 `"My Awesome App"` 赋予 `${appName}` 变量,最终呈现到前端页面上[^1]。 --- ### 总结 以上步骤涵盖了从基础依赖导入至实际应用开发全流程的操作指南。借助于 Spring Boot 自动化特性,整个流程变得极为简便高效。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值