3.13Thymeleaf前端集成

分类: 搭建单体商城服务

Thymeleaf 前端集成

Thymeleaf 是一个服务器端 Java 模板引擎,可以用于渲染 HTML 页面。本节将学习如何在 Spring Boot 3 中集成 Thymeleaf,实现前后端联调。

本节将学习:Thymeleaf 简介、模板配置、页面编写,以及表单提交。

Thymeleaf 简介

什么是 Thymeleaf?

Thymeleaf 是一个现代化的服务器端 Java 模板引擎,用于 Web 和独立环境。

Thymeleaf 特点

Thymeleaf 特点:

  1. 自然模板:HTML 模板可以直接在浏览器中打开
  2. 标准方言:支持 HTML5、XML、XHTML
  3. Spring 集成:与 Spring 框架深度集成
  4. 表达式语言:强大的表达式语言(OGNL、SpringEL)

依赖添加

Maven 依赖

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

模板配置

application.yml 配置

spring: thymeleaf: prefix: classpath:/templates/ suffix: .html mode: HTML encoding: UTF-8 cache: false # 开发环境关闭缓存

模板目录结构

src/
├── main/
│   ├── java/
│   └── resources/
│       ├── templates/
│       │   ├── index.html
│       │   ├── user/
│       │   │   ├── register.html
│       │   │   └── login.html
│       │   └── product/
│       │       ├── list.html
│       │       └── detail.html
│       └── static/
│           ├── css/
│           ├── js/
│           └── images/

页面编写

Controller 返回视图

package com.example.ecommerce.controller; import com.example.ecommerce.entity.User; import com.example.ecommerce.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; @Controller @RequestMapping("/") public class IndexController { @Autowired private UserService userService; @GetMapping public String index(Model model) { model.addAttribute("title", "E-commerce System"); return "index"; } @GetMapping("/users/register") public String registerPage(Model model) { model.addAttribute("user", new User()); return "user/register"; } @GetMapping("/users/login") public String loginPage(Model model) { return "user/login"; } }

Thymeleaf 模板示例

index.html:

<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title th:text="${title}">E-commerce System</title> <link rel="stylesheet" th:href="@{/css/style.css}"> </head> <body> <div class="container"> <h1 th:text="${title}">E-commerce System</h1> <nav> <a th:href="@{/users/register}">Register</a> <a th:href="@{/users/login}">Login</a> <a th:href="@{/products}">Products</a> </nav> </div> </body> </html>

Thymeleaf 常用语法

常用语法:

  • th:text="${variable}":输出文本
  • th:href="@{/path}":设置链接
  • th:if="${condition}":条件判断
  • th:each="item : ${list}":循环
  • th:object="${object}":对象绑定

表单提交

注册表单

user/register.html:

<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>User Registration</title> </head> <body> <div class="container"> <h1>User Registration</h1> <form th:action="@{/api/users/register}" th:object="${user}" method="post"> <div> <label>Username:</label> <input type="text" th:field="*{username}" required> </div> <div> <label>Email:</label> <input type="email" th:field="*{email}" required> </div> <div> <label>Password:</label> <input type="password" th:field="*{password}" required> </div> <div> <button type="submit">Register</button> </div> </form> </div> </body> </html>

表单处理

@Controller @RequestMapping("/users") public class UserViewController { @Autowired private UserService userService; @PostMapping("/register") public String register(@ModelAttribute User user, Model model) { try { User registered = userService.register(user); model.addAttribute("message", "Registration successful"); return "user/login"; } catch (BusinessException e) { model.addAttribute("error", e.getMessage()); model.addAttribute("user", user); return "user/register"; } } }

数据绑定

列表展示

product/list.html:

<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Product List</title> </head> <body> <div class="container"> <h1>Product List</h1> <table> <thead> <tr> <th>ID</th> <th>Name</th> <th>Price</th> <th>Stock</th> <th>Action</th> </tr> </thead> <tbody> <tr th:each="product : ${products}"> <td th:text="${product.id}">1</td> <td th:text="${product.name}">Product Name</td> <td th:text="${product.price}">99.99</td> <td th:text="${product.stock}">100</td> <td> <a th:href="@{/products/{id}(id=${product.id})}">View</a> </td> </tr> </tbody> </table> </div> </body> </html>

Controller 实现

@Controller @RequestMapping("/products") public class ProductViewController { @Autowired private ProductService productService; @GetMapping public String listProducts( @RequestParam(defaultValue = "1") Integer current, @RequestParam(defaultValue = "10") Integer size, Model model ) { Page<Product> page = productService.getProductList(current, size, null); model.addAttribute("products", page.getRecords()); model.addAttribute("current", current); model.addAttribute("total", page.getTotal()); return "product/list"; } @GetMapping("/{id}") public String productDetail(@PathVariable Long id, Model model) { Product product = productService.getProductDetail(id); model.addAttribute("product", product); return "product/detail"; } }

条件渲染

条件判断示例

<div th:if="${user != null}"> <p>Welcome, <span th:text="${user.username}">User</span>!</p> <a th:href="@{/users/logout}">Logout</a> </div> <div th:unless="${user != null}"> <a th:href="@{/users/login}">Login</a> <a th:href="@{/users/register}">Register</a> </div>

官方资源

本节小结

在本节中,我们学习了:

第一个是 Thymeleaf 简介。 Thymeleaf 是一个服务器端 Java 模板引擎。

第二个是模板配置。 配置模板路径、后缀、编码等。

第三个是页面编写。 使用 Thymeleaf 语法编写 HTML 模板。

第四个是表单提交。 使用 Thymeleaf 表单绑定处理表单提交。

这就是 Thymeleaf 前端集成。通过 Thymeleaf,我们可以快速实现前后端联调。

在下一节,我们将学习如何进行前后端联调测试,验证系统功能。