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
Server-Side Rendering (SSR) with React Hooks
Server-side rendering (SSR) is a technique used to render web pages on the server side and send the fully rendered page to the client's browser. This approach offers benefits such as improved SEO and faster initial page loads. With the introduction of React Hooks, SSR implementation has become even
4 min read
Ultimate Guide to Server-Side Rendering (SSR) with Vite and ReactJS
Server-side rendering (this practice allows making web pages since the browser only enables blank pages) can be defined as one of the current trends in web development. SSR offers many advantages â performance improvement, SEO enhancement, and even convenience for users. As opposed to client-side re
10 min read
How to Set Up Vite for Server-Side Rendering (SSR)?
Vite is a build tool that can be integrated with most modern JS web frameworks like React, Vue, Next.js, or even vanillaJS, and offers a variety of features like Hot Module Reloading (HMR), etc. In this article, we will learn how to setup vite using vanillaJS and SSR. Steps to Set Up Vite for Server
2 min read
Importance of View Engines in server-side rendering(SSR)
A view engine is a tool used in web development to create dynamic HTML content based on data from the server. It acts as a template processor that allows you to integrate data with predefined HTML templates easily. In this article, we will learn about the Importance of view engines on server side re
3 min read
Server Side Rendering using Express.js And EJS Template Engine
Server-side rendering involves generating HTML on the server and sending it to the client, as opposed to generating it on the client side using JavaScript. This improves initial load time, and SEO, and enables dynamic content generation. Express is a popular web application framework for NodeJS, and
3 min read
Spring Boot - Thymeleaf with Example
Thymeleaf is a server-side Java-based template engine for both web and standalone environments, capable of processing HTML, XML, JavaScript, CSS and even plain text. It is more powerful than JPS and responsible for dynamic content rendering on UI. The engine allows a parallel work of the backend and
6 min read
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
New Features of Spring MVC 6.0 and Thymeleaf 3.0
In this article, we will explore the latest features of Spring MVC 6.0 and Thymeleaf 3.0 and how they can be leveraged to develop enterprise applications. Spring MVC is a fundamental and broader part of the Spring Framework. It is used to develop Java-based applications. Spring MVC uses a front cont
5 min read
How to Integrate Keycloak with Spring Boot and Spring Security?
Keycloak is Open Source Identity and Access Management (IAM) solution developed by Red Hat. By using this you can add authentication to applications and secure services with minimum effort. No need to deal with storing users or authenticating users. Keycloak provides user federation, strong authenti
2 min read
Server-Side Rendering in Angular
With fast and efficient web applications, developers are continually seeking ways to enhance performance, user experience, and search engine optimization (SEO). One such strategy is server-side rendering (SSR). In this article, we will see what SSR is, why it is important, and how to implement it in
5 min read