本文演示了如何使用 Thymeleaf 将对象传递给 Spring MVC 应用程序中的模态对话框。通过为每个对象创建唯一的模态对话框并使用 Thymeleaf 的动态数据绑定功能,我们能够将相关内容传递给模态对话框并以交互方式显示它。
在 Web 应用程序中创建模态对话框是用户交互的常见要求,例如显示表单、确认操作或呈现信息。在带有Thymeleaf的Spring应用程序中,将动态数据传递给模态对话框可显著增强用户交互性。
在本文中,我们将介绍在 Thymeleaf 中实现模态对话框并向其传递对象的过程。
Maven 依赖项 在开始之前,让我们确保 Thymeleaf 在我们的 Spring MVC 应用程序中正确配置。我们需要在 pom.xml 文件中包含thymeleaf和thymeleaf-spring5依赖项:
<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> |
定义数据模型 接下来,让我们定义一个Book模型类。此类将表示我们要传递给模式对话框的数据。它包含id和name等属性,这些属性将用于显示每本书的相关信息:
public class Book { private int id; private String name; // constructor // getters and setters } |
创建控制器 现在,让我们实现一个 Spring Controller,准备一个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(1, "Book 2")); books.add(new Book(1, "Book 2")); model.addAttribute("books", books); return "listBooksWithModal.html"; } |
创建Thymeleaf模板 现在,让我们关注 Thymeleaf 模板,当用户单击“查看详细信息”按钮时,它将显示书籍列表并打开模态对话框。
在这个模板中,我们将Book对象传递给一个模态对话框,该对话框显示书籍的 ID 和名称等详细信息:
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <title>Book List with Modals</title> </head> <body> <div> <h1>Book List</h1> <table border="1"> <thead> <tr> <th>Book ID</th> <th>Book Name</th> <th>Action</th> </tr> </thead> <tbody> <tr th:each="book : ${books}"> <td th:text="${book.id}"></td> <td th:text="${book.name}"></td> <td> <!-- Button to open modal for the selected book --> <button th:attr="onclick=|showModal('infoModal' + ${book.id})|">View Details</button> </td> </tr> </tbody> </table> </div> <!-- Modal template for each book --> <div th:each="book : ${books}" th:attr="id=${'infoModal' + book.id}" style="display: none;"> <div> <h3>Book Details</h3> <p><strong>ID:</strong> <span th:text="${book.id}"></span></p> <p><strong>Name:</strong> <span th:text="${book.name}"></span></p> <button th:attr="onclick=|hideModal('infoModal' + ${book.id})|">Close</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> |
该模板以表格形式显示书籍列表,每行对应一本特定书籍。此结构让用户可以轻松查看每本书的基本信息,例如其 ID 和名称。此外,每本书都有一个“查看详细信息”按钮。单击此按钮时,会触发模式以显示有关所选书籍的更多详细信息。
在模态框中,Thymeleaf 的th:text属性会动态填充内容。当用户点击特定图书的“查看详细信息”按钮时,模态框会显示该图书的正确详细信息,例如其 ID 和名称。服务器通过模型生成模态框 ID,Thymeleaf 呈现内容,并将其绑定到模态框的 HTML 元素。
此外,我们根据图书的 ID 为每个模式分配一个唯一的 ID。这可确保当用户与“查看详细信息”按钮交互时显示正确的模式。模式 ID 是使用infoModal{id}格式动态生成的,其中{id}替换为实际图书 ID。因此,所选图书对象将显示正确的模式。
总体而言,模板结构有助于用户与书籍列表进行交互。他们无需离开页面即可查看每本书的更多详细信息,从而带来流畅高效的用户体验。
结果 在本节中,我们将展示渲染的模板,以说明 Thymeleaf 模板的实际效果。表格列出了书籍,每行显示书籍的 ID、名称和“查看详细信息”按钮.