Pass Object To Modal Dialog In Thymeleaf Example
Thymeleaf is a popular templating engine in the Spring ecosystem. One common requirement is passing data to a modal dialog for display or interaction. Let us delve into understanding how Thymeleaf can be used to pass an object to a modal dialog, enabling dynamic and interactive user interfaces in Java-based web applications.
1. What is Thymeleaf?
Thymeleaf is a modern, server-side Java template engine for web and standalone environments. It is primarily used for rendering HTML, XML, and other types of documents in Java-based web applications. Thymeleaf is commonly integrated with the Spring Framework, making it a popular choice for developing dynamic web pages in Java. Its core feature is the ability to generate HTML content with dynamic values, allowing for the creation of interactive web applications.
Thymeleaf is known for its rich integration with Spring MVC, allowing developers to easily render views and pass data from controllers to templates. One of its key strengths is its natural templating approach, where Thymeleaf templates are also valid HTML files, making them easy to work with both on the server side and in the development process. Developers can edit and test the templates independently of the application.
Some of the main advantages of Thymeleaf include its flexibility, ease of use, and extensibility. It supports a wide range of features such as conditional logic, iteration, and templating with reusable fragments. Thymeleaf also promotes cleaner and more readable code with its intuitive syntax, making it easier to maintain and scale web applications. Furthermore, its ability to handle complex layouts, integrate with Spring’s model-view-controller architecture, and process dynamic content in real time provides powerful tools for developers to build responsive, data-driven web applications.
2. Maven Dependencies
First, ensure you have the required dependencies in your pom.xml
file:
<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>
3. Defining the Data Model
Create a simple data model class. For this example, let’s define a Product
class:
public class Product { private Long id; private String name; private double price; // Getters and Setters }
4. Creating the Controller
Next, create a Spring MVC controller to handle requests and pass data to the view:
@Controller public class ProductController { @GetMapping("/products") public String showProducts(Model model) { List<Product> products = Arrays.asList( new Product(1L, "Product 1", 10.0), new Product(2L, "Product 2", 20.0) ); model.addAttribute("products", products); return "product-list"; } }
4.1 Code Explanation
In this code, a Spring MVC controller class named ProductController
is defined to handle HTTP requests related to products. The class is annotated with @Controller
, which indicates that it is a controller responsible for managing web requests.
The method showProducts
is mapped to the HTTP GET request for the /products
URL using the @GetMapping
annotation. When a user accesses this URL, the method is executed. Inside the method, a list of Product
objects is created using Arrays.asList()
to simulate a small dataset of products. Each Product
object contains an id
, name
, and price
, such as “Product 1” and “Product 2”.
The products
list is then added to the model with the model.addAttribute()
method, making it accessible to the Thymeleaf template. The key "products"
is used to reference this data within the template.
Lastly, the method returns the view name "product-list"
, which corresponds to the Thymeleaf template file product-list.html
. This template will be rendered, displaying the list of products to the user.
5. Creating the Thymeleaf Template
Create a Thymeleaf template named product-list.html
to display the product list and trigger the modal dialog:
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <title>Product List</title> <link rel="stylesheet" href="https://www.javacodegeeks.com/wp-content/litespeed/localres/aHR0cHM6Ly9tYXhjZG4uYm9vdHN0cmFwY2RuLmNvbS8=bootstrap/4.0.0/css/bootstrap.min.css"> <script src="https://www.javacodegeeks.com/wp-content/litespeed/localres/aHR0cHM6Ly9jb2RlLmpxdWVyeS5jb20vjquery-3.2.1.slim.min.js"></script> <script src="https://www.javacodegeeks.com/wp-content/litespeed/localres/aHR0cHM6Ly9jZG5qcy5jbG91ZGZsYXJlLmNvbS8=ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script> <script src="https://www.javacodegeeks.com/wp-content/litespeed/localres/aHR0cHM6Ly9tYXhjZG4uYm9vdHN0cmFwY2RuLmNvbS8=bootstrap/4.0.0/js/bootstrap.min.js"></script> </head> <body> <div class="container"> <h1>Product List</h1> <table class="table table-bordered"> <thead> <tr> <th>ID</th> <th>Name</th> <th>Price</th> <th>Actions</th> </tr> </thead> <tbody> <tr th:each="product : ${products}"> <td th:text="${product.id}"></td> <td th:text="${product.name}"></td> <td th:text="${product.price}"></td> <td> <button class="btn btn-primary" th:data-id="${product.id}" th:data-name="${product.name}" th:data-price="${product.price}" data-toggle="modal" data-target="#productModal"> View </button> </td> </tr> </tbody> </table> </div> <!-- Modal --> <div class="modal fade" id="productModal" tabindex="-1" role="dialog"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title">Product Details</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span> </button> </div> <div class="modal-body"> <p>ID: <span id="product-id"></span></p> <p>Name: <span id="product-name"></span></p> <p>Price: <span id="product-price"></span></p> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> </div> </div> </div> </div> <script> $('#productModal').on('show.bs.modal', function (event) { var button = $(event.relatedTarget); var id = button.data('id'); var name = button.data('name'); var price = button.data('price'); var modal = $(this); modal.find('#product-id').text(id); modal.find('#product-name').text(name); modal.find('#product-price').text(price); }); </script> </body> </html>
5.1 Code Explanation
This HTML code creates a dynamic product list page with a Bootstrap-based table, which displays product details and includes a modal dialog to show additional product information when a user clicks a button.
The body of the page contains a <div class="container">
element to center the content. Inside, a heading (<h1>
) and a table (<table>
) are used to display the list of products. The table headers include columns for the product ID, name, price, and actions. A <tbody>
section is used to dynamically populate the product rows, with Thymeleaf’s th:each
attribute iterating over the products
list passed from the controller. Each product’s ID, name, and price are injected into the respective table cells using the th:text
attribute.
For each product, there is a “View” button that triggers a modal dialog. The button includes the th:data-*
attributes to pass the product’s data (ID, name, price) to the modal, and it also has attributes like data-toggle="modal"
and data-target="#productModal"
to specify that it will open the modal dialog when clicked.
The modal itself is defined inside a <div class="modal">
element, which contains a header with a title and a close button, a body where the product details will be shown, and a footer with another close button. The product details are dynamically inserted into the modal when it is triggered, using jQuery. Specifically, the $('#productModal').on('show.bs.modal', function(event))
script listens for the modal’s opening event, retrieves the data attributes from the clicked button and updates the modal’s content accordingly. The product’s ID, name, and price are displayed inside the modal by setting the text of the corresponding <span>
elements with the values passed from the button.
6. Result
When you navigate to the /products
endpoint, the server will process the request, fetch the product data (typically from a database or mock data in the controller), and render the product-list.html
template. This will result in a page displaying a table of products, each with an ID, name, and price. The table is styled using Bootstrap’s table
and table-bordered
classes to ensure it looks clean and organized. Each product row contains a “View” button, which triggers a modal dialog with detailed product information when clicked.
Upon clicking the “View” button, a modal dialog will appear, displaying the product details such as its ID, name, and price. These details are dynamically passed from the button to the modal using the th:data-id
, th:data-name
, and th:data-price
attributes, which store the respective product’s values. The jQuery script embedded within the page listens for the modal’s show event and updates the modal content with the product’s information by selecting the corresponding <span>
elements and setting their text content to the product’s ID, name, and price.
Additionally, the modal includes a close button that allows the user to dismiss the modal and return to the main product list. The modal uses Bootstrap’s built-in functionality to handle opening, closing and transitions smoothly. This seamless interaction between the product list and modal is powered by Bootstrap’s modal components and Thymeleaf’s dynamic rendering of the data.
7. Conclusion
In this article, we explored how to pass an object to a modal dialog in Thymeleaf. We discussed the process of configuring the data model, controller, and Thymeleaf template to achieve this functionality. By implementing this method, you can dynamically transfer data to modals, improving user interaction and experience in your web applications.