1. 概述

在Web应用中创建模态对话框是常见需求,常用于显示表单、确认操作或展示信息。在Spring MVC与Thymeleaf结合的项目中,向模态对话框传递动态数据能显著提升用户交互体验。

本文将演示如何在Thymeleaf中实现模态对话框,并向其传递对象数据。

2. Maven依赖

首先确保Thymeleaf在Spring MVC项目中正确配置。在pom.xml中添加以下依赖:

<dependency>
    <groupId>org.thymeleaf</groupId>
    <artifactId>thymeleaf</artifactId>
    <version>3.1.2.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.thymeleaf</groupId>
    <artifactId>thymeleaf-spring5</artifactId>
    <version>3.1.2.RELEASE</version>
</dependency>

这些依赖使Spring MVC能够无缝处理Thymeleaf视图并渲染动态内容。

3. 定义数据模型

创建一个Book模型类,表示要传递给模态对话框的数据:

public class Book {
    private int id;
    private String name;

    // 构造方法
    // getter和setter
}

这个类包含idname属性,用于在模态框中展示书籍信息。

4. 创建控制器

实现Spring控制器,准备Book对象列表并传递给Thymeleaf视图:

@GetMapping("/listBooksWithModal")
public String listBooks(Model model) {
    List<Book> books = new ArrayList<>();
    books.add(new Book(1, "Book 1"));
    books.add(new Book(2, "Book 2"));
    books.add(new Book(3, "Book 3"));
    model.addAttribute("books", books);
    return "listBooksWithModal.html";
}

listBooks()方法准备书籍列表并添加到模型中,使数据在listBooksWithModal.html模板中可用。

5. 创建Thymeleaf模板

下面是核心模板,展示书籍列表并实现点击"查看详情"按钮打开模态框:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>带模态框的书籍列表</title>
</head>
<body>

<div>
    <h1>书籍列表</h1>
    <table border="1">
        <thead>
        <tr>
            <th>书籍ID</th>
            <th>书名</th>
            <th>操作</th>
        </tr>
        </thead>
        <tbody>
        <tr th:each="book : ${books}">
            <td th:text="${book.id}"></td>
            <td th:text="${book.name}"></td>
            <td>
                <!-- 打开对应书籍模态框的按钮 -->
                <button th:attr="onclick=|showModal('infoModal' + ${book.id})|">查看详情</button>
            </td>
        </tr>
        </tbody>
    </table>
</div>

<!-- 每本书籍的模态框模板 -->
<div th:each="book : ${books}" th:attr="id=${'infoModal' + book.id}" style="display: none;">
    <div>
        <h3>书籍详情</h3>
        <p><strong>ID:</strong> <span th:text="${book.id}"></span></p>
        <p><strong>书名:</strong> <span th:text="${book.name}"></span></p>
        <button th:attr="onclick=|hideModal('infoModal' + ${book.id})|">关闭</button>
    </div>
</div>

<script>
    function showModal(modalId) {
        document.getElementById(modalId).style.display = 'block';
    }

    function hideModal(modalId) {
        document.getElementById(modalId).style.display = 'none';
    }
</script>

</body>
</html>

关键实现点:

动态内容绑定:使用th:text属性动态填充模态框内容
唯一标识符:通过infoModal{id}格式为每个模态框生成唯一ID
精准触发:点击按钮时通过动态ID打开对应模态框

⚠️ 踩坑提示:确保每个模态框ID唯一,否则会出现多个模态框同时显示的bug

6. 运行效果

以下是模板渲染后的实际效果:

书籍列表页面
书籍列表

点击"查看详情"后的模态框
书籍详情

7. 总结

本文演示了在Spring MVC应用中,如何通过Thymeleaf向模态对话框传递对象数据。核心思路包括:

  1. 为每个对象创建独立模态框
  2. 利用Thymeleaf的动态数据绑定能力
  3. 通过唯一ID实现精准交互

这种实现方式既保持了页面流畅性,又提供了良好的用户体验,适合需要展示详细信息的场景。


原始标题:How to Pass Object to Modal Dialog in Thymeleaf? | Baeldung