Creating a Web Application with Thymeleaf and HTMX
Posted on June 9, 2024
In this blog post, we will create a web application using Spring Boot, Thymeleaf, and HTMX. We will build a CRUD (Create, Read, Update, Delete) application for managing a list of persons. This post will guide you through the code and explain each part to help you understand the functionality.
Start by creating a Spring Boot project and add the necessary dependencies for Thymeleaf. You can use the following dependencies in your pom.xml:
<dependencies><!-- Other dependencies --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId></dependency><!-- Other dependencies --></dependencies>
Creating the Controller
Our controller, HtmxPersonController, will handle the CRUD operations and return the appropriate views. Here’s the complete code for the controller:
Explanation of the Code
@Controller: Indicates that this class is a Spring MVC controller.
@RequestMapping(“/person-crud-htmx”): Maps requests to /person-crud-htmx to this controller.
private final PersonRepository personRepository: Injects the repository for CRUD operations.
@GetMapping: Handles GET requests.
@PostMapping: Handles POST requests.
@DeleteMapping: Handles DELETE requests.
PageRequest.of(page, size): Creates a pageable object for pagination.
model.addAttribute(“key”, value): Adds attributes to the model to be used in the view.
Designing the HTML Template
The Thymeleaf template, person-crud-htmx.html, will render the person list and handle dynamic updates using HTMX. Here’s the complete template:
Explanation of the HTML
th:attr=”hx-get=@{/person-crud-htmx/htmx/form(page=${currentPage})}” hx-target=”#person-dialog” hx-trigger=”click”: When the “Add Person” button is clicked, it sends an HTMX request to get the form fragment and displays it in the dialog.
th:each=”person : ${persons}”: Iterates over the list of persons.
th:text=”${person.firstName}”: Sets the text content to the person’s first name.
hx-get, hx-delete: HTMX attributes for sending GET and DELETE requests.
th:fragment=”personRows(persons, currentPage)”: Defines a Thymeleaf fragment for the table rows.
th:fragment=”pagination(totalPages, currentPage, size)”: Defines a Thymeleaf fragment for pagination.
htmx:afterSwap: Shows the dialog after the form is loaded.
htmx:beforeRequest: Closes the dialog before making a new request.
Conclusion
By following this guide, you have created a dynamic web application using Spring Boot, Thymeleaf, and HTMX. This application allows you to perform CRUD operations with a modern and responsive user interface. Explore further by adding more features and enhancing the UI to suit your needs.