Introduction
Thymeleaf is a Java templating engine that works well with Spring applications, allowing developers to create dynamic, data-driven web pages with simple and readable templates. It lets you preview your templates in the browser before connecting to your backend.
Spring Boot simplifies the development of Spring-based applications with default configurations and tools, enabling you to quickly set up and run your app. When combined with Thymeleaf, Spring Boot helps you build dynamic, maintainable web applications with minimal configuration, speeding up development.
In this blog, we’ll show you how to integrate Thymeleaf with Spring Boot to create dynamic web pages that display data from your app. We’ll cover setting up a Spring Boot project, configuring Thymeleaf, and creating templates for dynamic content. By the end, you’ll know how to use both technologies together to boost your web development projects.
Prerequisites
- Basic Knowledge of Java : Understanding Java programming is essential since both Thymeleaf and Spring Boot are Java-based frameworks.
- Java Development Kit (JDK) : Ensure you have JDK 8 or higher installed on your system.
- Integrated Development Environment (IDE) : An IDE like IntelliJ IDEA, Eclipse, or Spring Tool Suite will help you manage your project efficiently.
- Maven or Gradle : These build tools are used to manage project dependencies. You should be familiar with either Maven or Gradle.
- Spring Boot : Basic understanding of Spring Boot, including how to create a Spring Boot project and run it.
- HTML/CSS : Basic knowledge of HTML and CSS is necessary for creating and styling your web pages.
What is Thymeleaf ?
Thymeleaf is a modern, server-side Java template engine designed for web and standalone applications. It allows developers to generate dynamic content by processing and rendering HTML, XML, JavaScript, CSS, and other text files. With its seamless integration into the Spring Framework, especially Spring MVC, Thymeleaf is a go-to choice for developers working with Java-based web applications.
Key Features of Thymeleaf
- Dynamic Data Rendering : Thymeleaf makes it easy to dynamically inject data into your templates. This allows you to generate content based on the data from your backend. For instance, you can display user information, product details, or any dynamic content fetched from your database.
- Conditional Rendering : Need to display certain elements based on specific conditions? Thymeleaf allows you to add if-else logic directly into your templates. This way, you can control whether an element appears or not based on dynamic data.
- Loops : Thymeleaf also supports loops, which is handy when displaying lists, arrays, or collections. Whether you want to show a list of products or iterate over user comments, Thymeleaf makes it simple to loop through data and render it in HTML.
- Reusability with Fragments : Another powerful feature is the ability to create reusable fragments. With Thymeleaf, you can define fragments (like headers, footers, or navigation bars) and include them in multiple templates. This reduces code duplication and keeps your application’s layout consistent.
Why Use Thymeleaf ?
Thymeleaf stands out as a templating engine for several reasons:
- Ease of Integration : It integrates effortlessly with Spring Boot, making it the preferred choice for developers working within the Spring ecosystem.
- Readable Templates : Thymeleaf’s natural templating system allows templates to be written as standard HTML, which makes it simple for designers to work with and view in the browser before connecting to the backend.
- Flexible and Powerful : With features like conditional rendering, iteration, and the ability to easily inject dynamic content, you can create sophisticated, data-driven web pages with minimal coding effort.
How Thymeleaf Works?
Thymeleaf is a Java-based templating engine that integrates seamlessly with Spring Boot to generate dynamic web pages. It processes HTML templates on the server side, replacing placeholders with data passed from the backend. This allows you to create data-driven web pages while maintaining clean, readable templates. With features like conditional rendering, loops, and reusable fragments, Thymeleaf makes it easy to develop interactive web applications. It works by processing templates with data from the controller and sending the fully rendered HTML to the client’s browser.
How to Integrate Thymeleaf with a Spring Boot Application
Step 1 : Add Thymeleaf Dependency
If you’re using Maven, add the following dependencies to your pom.xml file:
- Spring Web : This dependency is required for building web applications.
- Thymeleaf : This is the templating engine that you will use to create dynamic web pages.
org.springframework.boot
spring-boot-starter-thymeleaf
org.springframework.boot
spring-boot-starter-web
Step 2 : Configure Thymeleaf
You can configure Thymeleaf properties in your application.properties or application.yml file:
spring.thymeleaf.cache=false
spring.thymeleaf.suffix: .html
Step 3 : Create the User Model
The first step is to define the entity class that will represent the user.
@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = "User")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "userId")
private long userId;
@Column(name = "userName")
private String userName;
@Column(name = "email")
private String email;
}
Step 4 : Create the Repository
Now, create a repository interface that extends JpaRepository to handle CRUD operations for the User entity.
@Repository
public interface UserRepository extends JpaRepository {
}
Step 5 : Create the Service Layer
Next, create a service interface and its implementation to manage business logic related to users.
@Service
public class UserServicesImpl{
@Autowired
UserRepository userRepository;
public User addUSer(User user) {
return userRepository.save(user);
}
public List getUser() {
return userRepository.findAll();
}
Step 6 : Create the Controller
Now, let’s add a controller that will handle the HTTP requests, interact with the service layer, and pass data to Thymeleaf templates
@Controller
public class UserController {
@Autowired
UserServicesImpl userServices;
@Autowired
UserRepository userRepository;
@GetMapping("/")
public String viewHomePage(Model model) {
model.addAttribute("allUserList", userServices.getUser());
return "index";
}
@GetMapping("/addnew")
public String addNewEmployee(Model model) {
User user = new User();
model.addAttribute("user", user);
return "newUser";
}
@PostMapping("/save")
public String saveEmployee(@ModelAttribute("employee") User user) {
userServices.addUSer(user);
return "redirect:/";
}
@GetMapping("/deleteEmployee/{id}")
public String deleteEmployee(@PathVariable("id") Long id,Model model){
User user = userRepository.findById(id)
.orElseThrow(() -> new IllegalArgumentException("Invalid userId:" + id));
userRepository.delete(user);
model.addAttribute("candidates", userRepository.findAll());
return "index";
}
}
Step 7 : Create Thymeleaf Templates
- index.html – Displays the list of users and provides links to add and delete users.
User System
- newUser.html – A form to add a new user.
User
Step 8 : Run Your Application
After completing the above steps, run your Spring Boot application. You can visit http://localhost:8080/ to view the home page where you can manage users by adding and deleting them.
- add a new user
- Navigate to http://localhost:8080/addnew to see a form where you can add a new user.
- After submitting the form, the user will be saved and displayed on the home page.
- Delete a user
Before Deleting a User:
-
- The user appears in the list on the Home Page with their details (name and email).
- Next to each user, there is a Delete button that allows the admin to remove the user from the list.
After Deleting a User
- Once the Delete button is clicked, the user is removed from the list.
- The page is refreshed, and the deleted user no longer appears in the table.
Other Use Cases for Thymeleaf
Thymeleaf is a versatile templating engine that can be used in various scenarios to create dynamic, data-driven web applications.
- Dynamic Email Templates :
- Thymeleaf is commonly used to generate dynamic email content. You can build personalized email templates with Thymeleaf by injecting dynamic data (e.g., user name, purchase details) directly into the template before sending the email.
- Generating PDFs :
- Thymeleaf can be integrated with libraries like Thymeleaf + iText or Thymeleaf + Flying Saucer to generate dynamic PDFs from HTML templates. This is useful for generating invoices, reports, or any content that needs to be downloaded or printed.
- Form Validation
- You can use Thymeleaf to bind and validate form data. It can automatically generate form fields, display validation errors, and create input forms that bind to backend Java objects.
- Creating HTML Reports
- Use Thymeleaf to create customizable HTML reports from data in your backend. These reports can be dynamic and feature tables, charts, and other elements that are generated based on user input or data stored in a database.
- RESTful APIs with Dynamic Responses
- Thymeleaf can be used to dynamically render data for RESTful API responses. When building web applications with both server-side rendering and client-side APIs, Thymeleaf helps provide dynamic HTML pages while the backend can render data for API responses in JSON or XML.
- Localization/Internationalization (i18n)
- Thymeleaf’s support for internationalization (i18n) makes it easy to adapt the UI for different languages or regions. You can configure templates to display messages and content in various languages based on the user’s locale.
- Custom Error Pages
- With Thymeleaf, you can create custom error pages, such as 404, 500, etc. These pages can be dynamically rendered with specific messages or links depending on the error encountered by the user.
Want to Know More?
Thymeleaf’s capabilities extend far beyond these examples. If you’re interested in learning more about how to implement Thymeleaf in your own projects or if you need help with advanced configurations, feel free to Contact Us. We are here to guide you through every step of the way!
Conclusion
Integrating Thymeleaf with Spring Boot lets you build dynamic and interactive web applications with ease. Thymeleaf’s simple HTML-like templates make it easy to work with, especially when combined with Spring Boot’s powerful features. In this blog, we showed how to set up Thymeleaf and create a basic user management app with CRUD operations.
With this foundation, you can easily add more features like authentication or validation. Thymeleaf is a great choice for building maintainable and efficient web applications in Java.