Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
Spring Boot - How Thymeleaf Works?
Next article icon

Spring Boot - How Thymeleaf Works?

Last Updated : 09 Jan, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Thymeleaf is a Java library, and template engine used to parse and render the data produced by the application to template files - thus providing transformation. It is just like HTML but is provided with more attributes for working with rendered data. It allows caching of the parsed data/file to increase efficiency while in production. Types of templates it can process are - HTML, JAVASCRIPT, CSS, XML, TEXT, and RAW.

Template engines used with Spring-Boot:

  • Thymeleaf
  • FreeMarker
  • Mustache
  • Groovy
  • Java Server Pages

How Thymeleaf work with Spring-Boot?

  1. Thymeleaf follows a De-Coupled Architecture - It is unaware of any web framework.
  2. In the same way, it is unaware of Spring's abstraction of the model and thus cannot handle the data that the controller places in the Model.
  3. When Spring-Boot's autoconfiguration detects Thymeleaf in the classpath, it creates beans supporting Thymeleaf view for Spring MVC.
  4. It can work with request attributes of Servlet.
  5. Therefore, Spring copies the model data into request attributes that the Thymeleaf template can work with.

Simple life-cycle of Thymeleaf template

Client-Server-View-Life-Cycle-of-Thymeleaf-TemplateView-Server-Client-Life-Cycle-of-Thymeleaf-Template

To use Thymeleaf, add its dependency in the project build.

Maven - pom.xml

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

Gradle - build.gradle

compile group: 'org.springframework.boot', name: 'spring-boot-starter-thymeleaf'

Place the template files in the following directory:

/src/main/resources/templates/
Project Structure

1. Rendering a single model attribute

To render an attribute, use 'th:text' attribute in Thymeleaf Template

<p th:text="${attributeKey}"> attributeValue will be placed here </p>

Controller (TemplateController.java) file:

Java
package gfg;  import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping;  @Controller @RequestMapping("/") public class TemplateController {          @GetMapping("/template1")     public String template(Model model) {         String msg = "Welcome to Thymeleaf Template";         // adding the attribute(key-value pair)         model.addAttribute("message", msg);         // returning the view name         return "index";     } } 

Template (index.html) file:

HTML
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"       xmlns:th="http://www.thymeleaf.org">  <head>  <title>GFG</title>  </head>  <body>  <h1>Welcome to GeeksForGeeks...</h1>  <div id="one">      <h1 th:text="${message}">        <span>message will print here</span>      </h1>   </div>  </body>  </html> 

Output:

Output Screen Template1

2. Rendering a collection

To render a collection, use 'th:each' attributes in the Thymeleaf template

<p th:each="variable:${collectionName}"> 
<span th:text=${variable}> items iterated will be placed here </span>
</p>

Note: span tag will be iterated as much as the number of collection items.

Controller (TemplateController2.java) file:

Java
package gfg;  import java.util.ArrayList; import java.util.List;  import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping;  @Controller @RequestMapping("/") public class TemplateController2 {          @GetMapping("/template2")     public String template(Model model) {         String message = "Top 5 Cloud Service Providers";         // creating a collection         List<String> list = new ArrayList<>();          list.add("Amazon Web Services");         list.add("Microsoft Azure");         list.add("Google Cloud");         list.add("Alibaba Cloud");         list.add("IBM Cloud");         model.addAttribute("message", message);         // adding the collection attribute         model.addAttribute("cloudProvider", list);         return "index2";     } } 

Template (index2.html) file:

HTML
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"  xmlns:th="http://www.thymeleaf.org">  <head>  <title>GFG2</title>  </head>  <body>  <div id="one">      <h2 th:text="${message}">        <span>message will print here</span>      </h2>   </div >  <div id="two" th:each="List:${cloudProvider}">      <ul>        <li>         <span th:text=${List}>items will print here</span>        </li>      </ul>  </div>  </body>  </html> 

Output:

Output Screen Template2

3. Binding data to object

Pre-requisites: 

  • Object to which values will be bound must have 'getter/setter' methods for each field.
  • You can use the 'Lombok' library to generate these methods by '@Data' annotation.

Add dependency of Lombok : Maven (pom.xml)

<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>

Using Thymeleaf, the input data is bound to the object using 'th:object' attribute

<form 
method="POST" th:object="${objectName}">
</form>

To map the input to a specific field of object use 'th:field' attribute

<input type="text" th:field="*{fieldName}" />

Controller (TemplateController3.java) file:

Java
package gfg;  import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping;  import gfg.os.OperatingSystem;  @Controller @RequestMapping("/template3") public class TemplateController3 {          @GetMapping     public String template(Model model) {         model.addAttribute("ops", new OperatingSystem());         return "index3";     }          @PostMapping     public String template( @ModelAttribute("ops") OperatingSystem os , Model model) {         model.addAttribute("message", os.getOS1()+" "+os.getOS2()+" "+os.getOS3());         return "index";     } } 

Class of the object to be bound (OperatingSystem.java) file:

Java
package gfg.os;  import lombok.Data;  @Data public class OperatingSystem {          public String OS1 ,OS2, OS3;      } 

Template (index3.html) file:

HTML
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"  xmlns:th="http://www.thymeleaf.org">  <head>  <title>GFG3</title>  </head>  <body>  <h1>Welcome to GeeksForGeeks...</h1>  <form method="POST" th:object="${ops}">           <div><label for="first">First OS</label></div>         <input id="first"  type="text" th:field="*{OS1}" />                  <div><label for="second">Second OS</label></div>         <input id="second"  type="text" th:field="*{OS2}" />                  <div><label for="third">Third OS</label></div>         <input id="third"  type="text" th:field="*{OS3}" />             <input type="submit" value="Send" />      </form>  </body>  </html> 

Output:

Output Screen Template3Output

Note: 

  • You can use other attributes of Thymeleaf as well.
  • The caching of the template is enabled by default.
  • You can turn off caching by specifying the following in the 'application.properties' file.

spring.thymeleaf.cache=false


Next Article
Spring Boot - How Thymeleaf Works?

P

pawardarshan461
Improve
Article Tags :
  • Java
Practice Tags :
  • Java

Similar Reads

    Spring Boot - Hello World
    Spring Boot is built on top of the Spring Framework and contains all the features of Spring. It has become a favorite of developers these days because of its rapid production-ready environment, which enables the developers to directly focus on the logic instead of struggling with the configuration a
    4 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
    Testing in Spring Boot
    In this article, we will be discussing Testing in Spring Boot. There are so many different testing approaches in Spring Boot used for deploying the application server. Testing in Spring Boot is an important feature of software development which ensures that your application behaves as per the requir
    4 min read
    Spring Boot Tutorial
    Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
    10 min read
    Spring Boot - Starter Test
    Spring Boot is built on top of the spring and contains all the features of spring. It is becoming a favorite of developers these days because of its rapid production-ready environment, which enables the developers to directly focus on the logic instead of struggling with the configuration and setup.
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences