springboot 下的Thymeleaf 前端渲染引擎

Thymeleaf 是一种现代化的服务器端 Java 模板引擎,常用于 Spring Boot 项目中,支持动态页面渲染和前后端分离。

1. 创建 Spring Boot 项目

  1. 使用 IDE(如 IntelliJ IDEA)创建一个 Spring Boot 项目。

  2. 在项目创建时,选择以下依赖: Spring Web:用于构建 Web 应用。 Thymeleaf:模板引擎支持。

<dependencies>
   <dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-thymeleaf</artifactId>
   </dependency>
   <dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-web</artifactId>
   </dependency>
</dependencies>

2. 配置 Thymeleaf

在 application.properties 或 application.yml 中添加以下配置:

spring.thymeleaf.cache=false # 禁用缓存(开发时使用)
spring.thymeleaf.prefix=classpath:/templates/ # 模板文件路径
spring.thymeleaf.suffix=.html # 模板文件后缀
spring.thymeleaf.encoding=UTF-8 # 文件编码

3. 编写 Controller

创建一个控制器类,用于处理请求并传递数据到模板:

package com.example.demo.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class DemoController {
   @GetMapping("/hello")
   public String hello(Model model) {
       model.addAttribute("message", "欢迎使用 Thymeleaf!");
       return "hello"; // 对应 templates/hello.html
   }
}

通过model.addAttribute来给html传输数据

4. 创建 Thymeleaf 模板

在 src/main/resources/templates 目录下创建 hello.html 文件:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
   <title>Thymeleaf 示例</title>
</head>
<body>
   <h1 th:text="${message}">默认消息</h1>
</body>
</html>

5. 启动项目并测试

  1. 启动 Spring Boot 项目。

  2. 在浏览器中访问 http://localhost:8080/hello,页面将显示传递的动态数据。

 

Thymeleaf 

  • 动静分离:Thymeleaf 支持直接打开 HTML 文件查看静态效果,方便前端开发。

  • 扩展性:可自定义方言和标签,满足复杂需求。

  • 性能优化:生产环境建议开启模板缓存(spring.thymeleaf.cache=true)。

 

注解用途示例
@Controller 标记为控制器 @Controller
@RequestMapping 映射请求路径 @RequestMapping("/user")
@GetMapping 映射GET请求 @GetMapping("/list")
@PostMapping 映射POST请求 @PostMapping("/save")
@ModelAttribute 绑定参数或添加模型数据 @ModelAttribute User user
@PathVariable 获取路径参数 @PathVariable Long id
@RequestParam 获取请求参数 @RequestParam String name
posted @ 2025-11-06 11:35  wangssd  阅读(12)  评论(0)    收藏  举报