Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Last Updated: Mar 27, 2024

Spring Boot Thymeleaf

Leveraging ChatGPT - GenAI as a Microsoft Data Expert
Speaker
Prerita Agarwal
Data Specialist @
23 Jul, 2024 @ 01:30 PM

Introduction

Spring Boot is a Java-based open-source framework for developing microservices. 

How cool would it be to get templates that didn't require an application server? Thymeleaf in Spring Boot fulfills this requirement.

In this article, we will learn about Spring Boot Thymeleaf. So, without any further ado, let's get started!

What is Spring Boot Thymeleaf?

Thymeleaf is a Java library that is open-source and licensed under the Apache License 2.0. It's a template engine that supports HTML5, XHTML, and XML. It's a Java template engine that works in web and non-web environments. It's ideal for HTML5 JVM web development today.

Thymeleaf's architecture allows for fast template processing due to the caching of parsed files. During execution, it performs as few I/O operations as possible. To display data generated by the application, it applies a set of transformations to template files. It can be used in web applications to serve XHTML/HTML5.

Thymeleaf's goal is to make templates more elegant and well-formed. It is built on the foundation of XML tags and attributes. Instead of explicitly writing that logic as code inside the template, these XML tags define predefined logic on the DOM (Document Object Model).

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Templates in Thymeleaf 

Our files are converted into well-formed XML files by Thymeleaf. It includes six different types of templates, as shown below:

  • HTML5
  • XHTML
  • Valid XHTML
  • Legacy HTML5
  • XML
  • Valid XML

 

All templates refer to well-formed valid XML files, with the exception of Legacy HTML5. We can use legacy HTML5 to render HTML5 tags on web pages, even if they aren't closed.

Why do we use Thymeleaf?

JSP is similar to HTML in many ways. However, unlike Thymeleaf, it is not completely HTML compatible. A Thymeleaf template file can be opened and displayed normally in the browser, but a JSP file cannot.

Variable expressions, similar to Spring EL and run on model attributes, asterisk expressions run on the form backing bean, hash expressions are used for internationalization, and link expressions rewrite URLs are all supported by Thymeleaf.

Thymeleaf Features

The features of Thymeleaf are as follows:

  • It can be used in web and non-web settings.
  • Its high-performance parsed template cache cuts down on I/O.
  • HTML5/ XML/ XHTML template engine written in Java.
  • It enables programmers to extend and create their dialects.
  • It is based on dialects, which are modular feature sets.
  • If necessary, it can be used as a template engine framework.
  • It supports a variety of template formats, including XML, XHTML, and HTML5.

Implementation of Thymeleaf

By adding a spring-boot-starter-thymeleaf dependency to our application's pom.xml file, we can use the Thymeleaf template engine. Spring Boot sets up the template engine to read the template from /resource/templates:

 

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

Example on Spring Boot Thymeleaf

Let's understand Spring Boot Thymeleaf by creating a Spring Boot application and implementing Thymeleaf template:

Step 1: Start Spring Initializr by typing http://start.spring.io into your browser.

Step 2: Give the name of the group com.codingninjas and the Artifact Id as Spring-boot-thymeleaf-view.

Step 3: Add the Spring Web and Thymeleaf dependencies as shown below:

Step 4: Select Generate button. The specifications are wrapped in a Jar file and downloaded to the local system when clicking the Generate button.

Step 5: Extract and paste the Jar file into the STS workspace.

Step 6: STS should be used to import the project folder.

File -> Import -> Existing Maven Projects -> Browse -> Then Select the spring-boot-thymeleaf-view-example folder-> Finish

Step 7: Create a model class in the com.codingninjas package. Ninja is the name of the model class we've created.

We've defined name and course variables and generated Getters and Setters in this class.

User.java

package com.codingninjas;    
public class Ninja  
{    
String name;    
String course;    
public String getName()   
{    
return name;    
}    
public void setName(String name)   
{    
this.name = name;    
}    
public String getCourse()   
{    
return course;    
}    
public void setCourse(String course)   
{    
this.course = course;    
}    
}    

 

Step 8: Make a controller class for your application. ControllerDemo is the name of the controller class we created.

ControllerDemo.java

package com.codingninja;    
import org.springframework.web.bind.annotation.ModelAttribute;    
import org.springframework.web.bind.annotation.RequestMapping;    
import org.springframework.web.bind.annotation.RequestMethod;    
import org.springframework.web.servlet.ModelAndView;    
import org.springframework.stereotype.Controller;    
@Controller    
public class ControllerDemo   
{    
@RequestMapping("/")    
public String index()  
{    
return"index";    
}    
@RequestMapping(value="/save", method=RequestMethod.POST)    
public ModelAndView save(@ModelAttribute User user)  
{    
ModelAndView modelAndView = new ModelAndView();    
modelAndView.setViewName("user-data");        
modelAndView.addObject("user", user);      
return modelAndView;    
}    
}  

 

Step 9: Create a Thymeleaf template with the name user-data in the project's templates folder.

Right-click on the templates folder -> New -> Other -> HTML File -> Next -> Give the File name -> Finish

Step 10: Include the following code in the template file.

<html lang="en" xmlns:th="http://www.thymeleaf.org">  

 

user-data.html

<html xmlns:th="https://thymeleaf.org">    
<table>    
<tr>    
<td><h4> Name: </h4></td>    
<td><h4 th:text="${user.name}"></h4></td>    
</tr>    
<tr>    
<td><h4> Course: </h4></td>    
<td><h4 th:text="${user.course}"></h4></td>    
</tr>    
</table>    
</html> 

 

Step 11: Create an HTML file in the templates folder. We've created a file called index in HTML.

index.html

<html lang="en">    
<head>    
<title>Index Page</title>    
</head>    
<body>    
<form action="save" method="post">    
<table>    
<tr>    
<td><label for="user-name">Name</label></td>    
<td><input type="text" name="name"></input></td>    
</tr>    
<tr>    
<td><label for="course">Course</label></td>    
<td><input type="text" name="name"></input></td>    
</tr>    
<tr>    
<td></td>    
<td><input type="submit" value="Submit"></input></td>    
</tr>    
</table>    
</form>    
</body>    
</html>  

 

Step 12: Add the properties listed below to the application.properties file:

spring.thymeleaf.cache=false  

spring.thymeleaf.suffix: .html

Step 13: Open the SpringBootThymeleafViewApplication.java file and run as Java Application.

SpringBootThymeleafViewApplication.java

package com.codingninjas;  
import org.springframework.boot.SpringApplication;  
import org.springframework.boot.autoconfigure.SpringBootApplication;  
@SpringBootApplication  
public class SpringBootThymeleafViewApplication   
{  
public static void main(String[] args)   
{  
SpringApplication.run(SpringBootThymeleafViewApplication.class, args);  
}  
}  

 

Step 14: Now open your browser and type http://localhost:8080 into the address bar. It displays the result as shown below:

 

Provide the Name and Course and select the Submit button:

 

The URL changes to http://localhost:8080/save after clicking the Submit button, and the user-data is displayed, as shown below:

 

Must Read Spring Tool Suite

FAQs

  1. What is Spring Boot?
    Spring Boot is a Java-based open-source framework for developing microservices. Pivotal Team created it, and it is used to create stand-alone and production-ready spring applications.
     
  2. What is Thymeleaf?
    Thymeleaf is a Java library that is open-source and licensed under the Apache License 2.0. It's a template engine that supports HTML5, XHTML, and XML. It's a Java template engine that works in web and non-web environments.
     
  3. What are the features of Spring Boot Thymeleaf?
    The features of Thymeleaf are as follows:
  • It can be used in web and non-web settings.
  • Its high-performance parsed template cache cuts down on I/O.
  • HTML5/ XML/ XHTML template engine written in Java.
  • It enables programmers to extend and create their dialects.
  • It is based on dialects, which are modular feature sets.
  • If necessary, it can be used as a template engine framework.
  • It supports a variety of template formats, including XML, XHTML, and HTML5.

 

Key Takeaways 

This article has learned about Spring Boot Thymeleaf features, use, and example application. 

You can also check our previous blogs on STS Download, Introduction to Spring BootSpring Boot Auto-configuration, Spring Boot Annotations, and Spring Boot CLI. You can also consider our Spring Boot Course to give your career an edge over others.

 

Thank you for reading!

 

Topics covered
1.
Introduction
2.
What is Spring Boot Thymeleaf?
3.
Templates in Thymeleaf 
4.
Why do we use Thymeleaf?
5.
Thymeleaf Features
6.
Implementation of Thymeleaf
7.
Example on Spring Boot Thymeleaf
8.
FAQs
9.
Key Takeaways