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 - Thymeleaf with Example
Next article icon

Spring Boot - Thymeleaf with Example

Last Updated : 13 Jun, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

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 frontend developers on the same view. It can directly access the java object and spring beans and bind them with UI. And it is mostly used with spring MVC when we create any web application. So let's start with an example to understand how Thymeleaf works with the Spring framework. 

Project Setup

Here we are going to perform crud operation on Employee dataset. So for building this we have to add certain dependencies which are listed in bulleted form or also in pom.xml. 

  • Spring Web (Build web, including RESTful, applications using Spring MVC. Uses Apache Tomcat as the default embedded container.)
  • Spring Data JPA (Persist data in SQL stores with Java Persistence API using Spring Data and Hibernate.)
  • Spring Boot Devtools (Provides fast application restarts, LiveReload, and configurations for enhanced development experience)
  • MySQL Driver (MySQL JDBC and R2DBC driver)
  • Thymeleaf ( server-side Java template engine for both web and standalone environments. Allows HTML to be correctly displayed in browsers and as static prototypes.)

POM.XML

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>2.6.2</version>         <relativePath/> <!-- lookup parent from repository -->     </parent>     <groupId>com.example</groupId>     <artifactId>thymeleaf</artifactId>     <version>0.0.1-SNAPSHOT</version>     <name>thymeleaf</name>     <description>Demo project for Spring Boot</description>     <properties>         <java.version>17</java.version>     </properties>     <dependencies>         <dependency>             <groupId>org.springframework.boot</groupId>             <artifactId>spring-boot-starter-data-jpa</artifactId>         </dependency>         <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>mysql</groupId>             <artifactId>mysql-connector-java</artifactId>             <scope>runtime</scope>         </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>             </plugin>         </plugins>     </build> </project> 

application.properties file

spring.jpa.hibernate.ddl-auto=update spring.datasource.url=jdbc:mysql://localhost:3306/emp spring.datasource.username=root spring.datasource.password=root spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQLInnoDBDialect logging.level.org.hibernate.SQL=DEBUG logging.level.org.hibernate.type=TRACE

Employee Pojo

This is the simple pojo class which is used to store the data of Employee. 

Java
package com.microservice.modal;  import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id;  @Entity public class Employee {     @Id     @GeneratedValue(strategy=GenerationType.IDENTITY)     private long id;     private String name;     private String email;          public long getId() {         return id;     }     public void setId(long id) {         this.id = id;     }     public String getName() {         return name;     }     public void setName(String name) {         this.name = name;     }     public String getEmail() {         return email;     }     public void setEmail(String email) {         this.email = email;     } } 

Employee Service interface and EmployeeServiceImpl class

Java
package com.microservice.service;  import java.util.List;  import com.microservice.modal.Employee;  public interface EmployeeServices {     List<Employee> getAllEmployee();     void save(Employee employee);     Employee getById(Long id);     void deleteViaId(long id); } 

EmployeeServiceImpl class which implements EmployeeSerivce interface methods

Java
package com.microservice.service;  import com.microservice.modal.Employee; import com.microservice.repository.EmployeeRepository; import java.util.List; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service;  @Service public class EmployeeServiceImpl     implements EmployeeServices {        @Autowired private EmployeeRepository empRepo;      @Override public List<Employee> getAllEmployee()     {         return empRepo.findAll();     }      @Override public void save(Employee employee)     {         empRepo.save(employee);     }      @Override public Employee getById(Long id)     {         Optional<Employee> optional = empRepo.findById(id);         Employee employee = null;         if (optional.isPresent())             employee = optional.get();         else             throw new RuntimeException(                 "Employee not found for id : " + id);         return employee;     }      @Override public void deleteViaId(long id)     {         empRepo.deleteById(id);     } } 

EmployeeRepository Interface

Here we are using JPA for communicating and saving the object into database.

Java
package com.microservice.repository;  import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository;  import com.microservice.modal.Employee;  @Repository public interface EmployeeRepository extends JpaRepository<Employee,Long> {  } 

EmployeeController class

This is the controller class it basically controls the flow of the data. It controls the data flow into model object and updates the view whenever data changes. So here we are mapping our object data with Thymeleaf. 

  • When user type the URL localhost:8080/ on browser than request goes to the viewHomePage() method and in this method we are fetching the list of employee and added it into the modal with key, value pair and return the index.html page. In index.html page the key (allemplist) is identified as a java object and Thymeleaf iterate over the list and generate dynamic content as per the user provided template.
  • /addNew -  when user clicks on Add Employee button than request goes to addNewEmployee() method. And in this method we simply create the empty object of the employee and send it back to newemployee.html so that user can fill the data in this empty object and when user hits on save button than /save mapping runs and get the object of the employee and save that object into database.
  • /showFormForUpdate/{id} - This mapping is for updating the existing employee data.
  • /deleteEmployee/{id} - This mapping is for deleting the existing employee data.
Java
package com.microservice.controller;  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.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping;  import com.microservice.modal.Employee; import com.microservice.service.EmployeeServiceImpl;  @Controller public class EmployeeController {      @Autowired     private EmployeeServiceImpl employeeServiceImpl;      @GetMapping("/")     public String viewHomePage(Model model) {         model.addAttribute("allemplist", employeeServiceImpl.getAllEmployee());         return "index";     }      @GetMapping("/addnew")     public String addNewEmployee(Model model) {         Employee employee = new Employee();         model.addAttribute("employee", employee);         return "newemployee";     }      @PostMapping("/save")     public String saveEmployee(@ModelAttribute("employee") Employee employee) {         employeeServiceImpl.save(employee);         return "redirect:/";     }      @GetMapping("/showFormForUpdate/{id}")     public String updateForm(@PathVariable(value = "id") long id, Model model) {         Employee employee = employeeServiceImpl.getById(id);         model.addAttribute("employee", employee);         return "update";     }      @GetMapping("/deleteEmployee/{id}")     public String deleteThroughId(@PathVariable(value = "id") long id) {         employeeServiceImpl.deleteViaId(id);         return "redirect:/";      } } 

index.html

This page is used to displaying the list of employee. Here we are iterating over the allemplist object which is sent by our controller from viewHomePage() method. 

HTML
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="ISO-8859-1"> <title>Employee</title> <link rel="stylesheet"     href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"     integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO"     crossorigin="anonymous"> </head> <body> <div class="container my-2" align="center">  <h3>Employee List</h3> <a th:href="@{/addnew}" class="btn btn-primary btn-sm mb-3" >Add Employee</a>     <table style="width:80%" border="1"             class = "table table-striped table-responsive-md">     <thead>   <tr>     <th>Name</th>     <th>Email</th>     <th>Action</th>   </tr>   </thead>   <tbody>   <tr th:each="employee:${allemplist}">         <td th:text="${employee.name}"></td>         <td th:text="${employee.email}"></td>         <td> <a th:href="@{/showFormForUpdate/{id}(id=${employee.id})}"                  class="btn btn-primary">Update</a>                 <a th:href="@{/deleteEmployee/{id}(id=${employee.id})}"                 class="btn btn-danger">Delete</a>     </td>   </tr>   </tbody> </table> </div> </body> </html> 

newemployee.html

This page is used to add new employee in the database. Here we simply provide the value in empty fields and click the submit button. Than the data of the employee goes to the saveEmployee() method and save the data into database. 

HTML
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="ISO-8859-1"> <title>Employee Management System</title> <link rel="stylesheet"     href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"     integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO"     crossorigin="anonymous"> </head> <body>     <div class="container">         <h1>Employee Management System</h1>         <hr>         <h2>Save Employee</h2>          <form action="#" th:action="@{/save}" th:object="${employee}"             method="POST">             <input type="text" th:field="*{name}" placeholder="Employee Name"                 class="form-control mb-4 col-4"> <input type="text"                 th:field="*{email}" placeholder="Employee Email"                 class="form-control mb-4 col-4">              <button type="submit" class="btn btn-info col-2">Save                 Employee</button>         </form>          <hr>          <a th:href="@{/}"> Back to Employee List</a>     </div> </body> </html> 

update.html

This page is used to update the data of existing employee. 

HTML
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="ISO-8859-1"> <title>Employee Management System</title>  <link rel="stylesheet"     href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"> </head> <body>     <div class="container">         <h1>Employee Management System</h1>         <hr>         <h2>Update Employee</h2>          <form action="#" th:action="@{/save}" th:object="${employee}"             method="POST">                          <!-- Add hidden form field to handle update -->             <input type="hidden" th:field="*{id}" />                          <input type="text" th:field="*{Name}" class="form-control mb-4 col-4">                                                  <input type="text" th:field="*{email}" class="form-control mb-4 col-4">                                  <button type="submit" class="btn btn-info col-2"> Update Employee</button>         </form>                  <hr>                  <a th:href = "@{/}"> Back to Employee List</a>     </div> </body> </html> 

Output:


Next Article
Spring Boot - Thymeleaf with Example

S

shubhamp338
Improve
Article Tags :
  • Java
  • Java-Spring-Boot
Practice Tags :
  • Java

Similar Reads

    Spring Boot - Packaging
    The Spring Framework was created to provide an open-source application framework to feature better infrastructure support for developing Java applications. It is one of the most popular Java Enterprise Edition (Java EE) frameworks, Spring framework helps developers in creating high-performing applic
    11 min read
    Spring Boot - JDBC
    Spring Boot JDBC is used to connect the Spring Boot application with JDBC by providing libraries and starter dependencies. Spring Boot JDBC has a level of control over the SQL queries that are being written. Spring Boot JDBC has simplified the work of Spring JDBC by automating the work and steps by
    8 min read
    Spring Boot - AOP After Throwing Advice
    Spring is widely used for creating scalable applications. For web applications Spring provides. Spring MVC is a widely used module of spring that is used to create scalable web applications. While Aspect-oriented programming(AOP) as the name suggests uses aspects in programming. It can be defined as
    6 min read
    Spring Boot - AOP After Returning Advice
    Prerequisite: Aspect Oriented Programming and AOP in Spring Framework Aspect-oriented programming(AOP) as the name suggests uses aspects in programming. It can be defined as the breaking of code into different modules, also known as modularisation, where the aspect is the key unit of modularity. Asp
    5 min read
    Multi-Module Project With Spring Boot
    Multi-Module project with Spring Boot refers to a project structure where multiple modules or subprojects are organized under a single parent project. Each module can represent a distinct component, functionality, or layer of the application, allowing for better organization, maintainability, and co
    6 min read
    Spring Boot - AOP After Advice
    Prerequisite: Aspect Oriented Programming and AOP in Spring Framework Aspect-oriented programming(AOP) as the name suggests uses aspects in programming. It can be defined as the breaking of code into different modules, also known as modularisation, where the aspect is the key unit of modularity. Asp
    5 min read
    Spring Boot - AOP Before Advice
    Aspect-oriented programming(AOP) as the name suggests uses aspects in programming. It can be defined as the breaking of code into different modules, also known as modularisation, where the aspect is the key unit of modularity. Aspects enable the implementation of crosscutting concerns such as transa
    4 min read
    Spring Boot - DevTools
    Spring Boot provides DevTools, a module designed to ease your development process, it improves the experience of developing applications resulting in optimizing the developer's productivity for building exceptional software.It aims to reduce development time, by intelligently detecting code changes
    5 min read
    Spring Boot - Dependency Management
    Spring Boot framework is the most popular web development framework. No doubt, it provides an abundance of essential features and a convenient way to handle those features. At the heart of Spring Boot is the 'Dependency Management' feature. Importance of Dependency ManagementCentralized Dependency M
    6 min read
    Spring Boot - Caching
    Spring Boot is a project that is built on top of the Spring Framework that provides an easier and faster way to set up, configure, and run both simple and web-based applications. It is one of the popular frameworks among developers these days because of its rapid production-ready environment which e
    6 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