Spring MVC – Integrate with Thymeleaf for Server-Side Rendering
Last Updated :
30 Aug, 2024
In modern web development, server-side rendering is crucial for creating fast, SEO-friendly, dynamic web pages. By integrating Spring MVC with Thymeleaf, developers can build powerful and flexible solutions for rendering HTML content on the server side. Thymeleaf, a natural templating engine, works seamlessly with Spring MVC, allowing developers to generate dynamic HTML content that's both easy to understand and maintain.
This article will guide you on how to integrate Thymeleaf with Spring MVC for server-side rendering in a Spring Boot application.
Integrating Spring MVC with Thymeleaf for Server-Side Rendering
Understanding Spring MVC
Spring MVC (Model-View-Controller) is a robust framework that follows the MVC pattern to build web applications. It separates the application into three distinct but interconnected components:
- Model: Represents the data or business logic of the application. It contains the data that is passed between the view and the controller.
- View: Responsible for rendering the user interface, i.e., the HTML content presented to the user.
- Controller: Manages user requests, processes input, and returns the view with the corresponding model data.
What is Thymeleaf?
Thymeleaf is a Java-based templating engine that allows you to process HTML, XML, JavaScript, CSS, and plain text. When integrated with Spring MVC, Thymeleaf dynamically generates content, providing an efficient way to create server-rendered web pages.
Key features of Thymeleaf include:
- Natural Templating: Thymeleaf templates can be opened directly in web browsers, allowing designers to work with HTML without disrupting development.
- Expression Language: Similar to JSP EL, Thymeleaf provides expressions to access variables, perform logical operations, and iterate over collections.
- Integration with Spring MVC: Thymeleaf is designed to integrate smoothly with Spring MVC, making it a preferred choice for many Spring-based applications.
- Modular Architecture: Supports custom dialects and expressions, enabling customization and extension according to project needs.
Implementation: Integrating Spring Boot with Thymeleaf for Server-Side Rendering
Step 1: Create a New Spring Boot Project
- Name:
spring-mvc-thymeleaf
- Language: Java
- Type: Maven
- Packaging: Jar
Click on the Next button.
Step 2: Add Dependencies
Add the following dependencies to your Spring Boot project:
- Spring Web
- Spring Boot DevTools
- Lombok
- Thymeleaf
Click on the Create button.
Project Structure
After the project created successfully, it will look like the below image:
Step 3: Configure Application Properties
In the application.properties
file, add:
spring.application.name=spring-mvc-thymeleaf
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
Step 4: Create the User
Class
Create the user class to represents the data of the Spring Boot application.
Java
package com.gfg.springmvcthymeleaf;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private String name;
private int age;
}
The User
class contains the name
and age
properties with corresponding getters and setters.
Step 5: Create the UserService Class
Create the UserService class to handle the bussiness logic of the Spring Boot application.
Java
package com.gfg.springmvcthymeleaf;
import org.springframework.stereotype.Service;
@Service
public class UserService {
public User getUserByName(String name) {
// In a real application, you would fetch user data from a database
return new User(name, 30); // Hard-coded for simplicity
}
}
The UserService
class provides a method to fetch user data, returning a hardcoded User
object for demonstration purposes.
Step 6: Create the UserController Class
Create the UserController class to handle the HTTP requests of the Spring Boot application.
Java
package com.gfg.springmvcthymeleaf;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/home")
public String home(Model model) {
model.addAttribute("message", "Welcome to Spring MVC with Thymeleaf!");
return "home";
}
@GetMapping("/welcome")
public String welcome(@RequestParam(name = "name", required = false, defaultValue = "User") String name, Model model) {
User user = userService.getUserByName(name);
model.addAttribute("user", user);
return "welcome";
}
}
- The
@Controller
annotation indicates that this class is a Spring MVC Controller. - The
home()
method handles the /home
endpoint and adds a message to the model, which is then displayed in the home.html
Thymeleaf template. - The
welcome()
method handles the /welcome
endpoint, takes the name
parameter, fetches the User
object using UserService
, and passes it to the welcome.html
template.
Step 7: Main class
This is the entry point of the Spring Boot application. No changes are required in the main class.
Java
package com.gfg.springmvcthymeleaf;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringMvcThymeleafApplication {
public static void main(String[] args) {
SpringApplication.run(SpringMvcThymeleafApplication.class, args);
}
}
Explaination:
- The @SpringBootApplication annotation enables the auto-configuration, component scanning, and configuration support for the Spring Boot application.
Step 8: Thymeleaf Templates
1. Create the HTML file named as home.html and put the below html code.
home.html
HTML
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Home Page</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f2f9f3; /* Light green background */
color: #2e7d32; /* Dark green text */
text-align: center;
padding: 50px;
}
h1 {
font-size: 2em;
color: #388e3c; /* Primary green color for heading */
}
a {
display: inline-block;
margin-top: 20px;
padding: 10px 20px;
background-color: #66bb6a; /* Light green button */
color: white;
text-decoration: none;
border-radius: 5px;
transition: background-color 0.3s;
}
a:hover {
background-color: #4caf50; /* Darker green on hover */
}
</style>
</head>
<body>
<h1 th:text="${message}">Default Welcome Message</h1>
<a href="/welcome?name=John">Go to Welcome Page</a>
</body>
</html>
Explaination:
- The
th:text
attribute sets the text content of the h1
element from the message
model attribute. - The hyperlink navigates to the welcome page.
2. Create another HTML file named as welcome.html and put the below html code.
welcome.html
HTML
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Welcome Page</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f2f9f3; /* Light green background */
color: #2e7d32; /* Dark green text */
text-align: center;
padding: 50px;
}
h1 {
font-size: 2em;
color: #388e3c; /* Primary green color for heading */
}
p {
font-size: 1.2em;
}
a {
display: inline-block;
margin-top: 20px;
padding: 10px 20px;
background-color: #66bb6a; /* Light green button */
color: white;
text-decoration: none;
border-radius: 5px;
transition: background-color 0.3s;
}
a:hover {
background-color: #4caf50; /* Darker green on hover */
}
</style>
</head>
<body>
<h1>Welcome, <span th:text="${user.name}">User</span>!</h1>
<p>Age: <span th:text="${user.age}">30</span></p>
<a href="/home">Back to Home</a>
</body>
</html>
The th:text
attribute dynamically replaces the content of the span
elements with the name
and age
properties of the User
object passed from the controller
pom.xml File
XML
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.3.3</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.gfg</groupId>
<artifactId>spring-mvc-thymeleaf</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring-mvc-thymeleaf</name>
<description>spring-mvc-thymeleaf</description>
<url/>
<licenses>
<license/>
</licenses>
<developers>
<developer/>
</developers>
<scm>
<connection/>
<developerConnection/>
<tag/>
<url/>
</scm>
<properties>
<java.version>17</java.version>
</properties>
<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>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
Step 9: Run the Application
After everything done, the application will start at port 8080.
Output:
1. Home Page:
URL: http://localhost:8080/home
2. Welcome Page
URL: http://localhost:8080/welcome?name=John
This example project demonstrates the how to set up the simple Spring MVC application with Thymeleaf for the server-side rendering. By the following this example, we can understand the basic of the integrating Thymeleaf with Spring MVC and create the dynamic web applications.
Similar Reads
How to Send Email with Thymeleaf Template in Spring Boot? Spring Boot is a framework for developing web applications. It simplifies development with features like auto-configuration, dependency management, and Spring Security. Thymeleaf, a Java template engine, is easy to use in Spring Boot. It handles XML files and integrates well with the Spring framewor
6 min read
Serve Static Resources With Spring It's essential to know about static resources, which are the resources that do not change frequently on a web page. To serve these static resources, Spring Boot comes with an inbuilt class called ResourceHttpRequestHandler in conjunction with the ResourceHandlerRegistry class. You can keep these sta
4 min read
Returning Image/Media Data with Spring MVC Spring MVC is a popular framework to build web applications in Java. One of the common requirements in web development is handling image or media data such as pictures, videos, or audio files. In Spring MVC, handling image or media data involves configuring a controller to receive requests for speci
3 min read
Spring MVC - ResourceBundleViewResolver Configuration ResourceBundleViewResolver in Spring MVC is used to resolve "view named" by view beans in the ".properties" file. View beans defined in the properties file are utilized by the ResourceBundleViewResolver to determine the view names. Using the Spring Web MVC Framework, the ResourceBundleViewResolver m
2 min read
Serverless Functions with Spring Cloud Function Serverless computing in Spring Boot is popular because of its simplicity and low cost. Working serverless allows us to focus on writing code without worrying about managing infrastructure. Spring Cloud Function is a framework that can enable serverless services using the Spring ecosystem. It allows
3 min read