• Java
    • JAXB Tutorial
      • What is JAXB
      • JAXB Marshalling Example
      • JAXB UnMarshalling Example
  • Spring Tutorial
    • Spring Core Tutorial
    • Spring MVC Tutorial
      • Quick Start
        • Flow Diagram
        • Hello World Example
        • Form Handling Example
      • Handler Mapping
        • BeanNameUrlHandlerMapping
        • ControllerClassNameHandlerMapping
        • SimpleUrlHandlerMapping
      • Validation & Exception Handling
        • Validation+Annotations
        • Validation+ResourceBundle
        • @ExceptionHandler
        • @ControllerAdvice
        • Custom Exception Handling
      • Form Tag Library
        • Textbox Example
        • TextArea Example
        • Password Example
        • Dropdown Box Example
        • Checkboxes Example
        • Radiobuttons Example
        • HiddenValue Example
      • Misc
        • Change Config file name
    • Spring Boot Tutorial
  • Hibernate Tutorial
  • REST Tutorial
    • JAX-RS REST @PathParam Example
    • JAX-RS REST @QueryParam Example
    • JAX-RS REST @DefaultValue Example
    • JAX-RS REST @Context Example
    • JAX-RS REST @MatrixParam Example
    • JAX-RS REST @FormParam Example
    • JAX-RS REST @Produces Example
    • JAX-RS REST @Consumes Example
    • JAX-RS REST @Produces both XML and JSON Example
    • JAX-RS REST @Consumes both XML and JSON Example
  • Miscellaneous
    • JSON Parser
      • Read a JSON file
      • Write JSON object to File
      • Read / Write JSON using GSON
      • Java Object to JSON using JAXB
    • CSV Parser
      • Read / Write CSV file
      • Read/Parse/Write CSV File – OpenCSV
      • Export data into a CSV File
      • CsvToBean and BeanToCsv – OpenCSV

JavaInterviewPoint

Java Development Tutorials

Spring Boot Thymeleaf Example

September 10, 2018 by javainterviewpoint Leave a Comment

Thymeleaf is a Java template engine for processing  HTML, XML, JavaScript, CSS, and text. In this Spring Boot Thymeleaf Example, we will learn how to configure Thymeleaf with Spring Boot Application and build a simple Employee Details app.

Integrate Thymeleaf with Spring Boot

In a Spring MVC application, we need to configure Thymeleaf Template Engine where as integrating Thymeleaf with Spring Boot is pretty simple, all we need to do is to add the following spring-boot-starter-thymeleaf dependency in our pom.xml

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

By Default, Spring Boot configures the Thymeleaf template engine to read template files from /src/main/resources/templates, So we need to make sure to place our html files under the templates folder

Folder Structure:

Spring Boot Thymeleaf Example

  1. Create a Maven project (maven-archetype-quickstart) “SpringBootThymeleaf” and create a package for our source files “com.javainterviewpoint” under  src/main/java 
  2. Now add the following dependency in the POM.xml
    <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	http://maven.apache.org/xsd/maven-4.0.0.xsd">
    	<modelVersion>4.0.0</modelVersion>
    
    	<groupId>com.javainterviewpoint</groupId>
    	<artifactId>SpringBootThymeleaf</artifactId>
    	<version>0.0.1-SNAPSHOT</version>
    	<packaging>jar</packaging>
    
    	<name>SpringBootThymeleaf</name>
    	<url>http://maven.apache.org</url>
    
    	<parent>
    		<groupId>org.springframework.boot</groupId>
    		<artifactId>spring-boot-starter-parent</artifactId>
    		<version>1.5.3.RELEASE</version>
    	</parent>
    
    	<properties>
    		<java.version>1.8</java.version>
    	</properties>
    
    	<dependencies>
    		<dependency>
    			<groupId>org.springframework.boot</groupId>
    			<artifactId>spring-boot-starter-thymeleaf</artifactId>
    		</dependency>
    	</dependencies>
    
    	<build>
    		<plugins>
    			<plugin>
    				<groupId>org.springframework.boot</groupId>
    				<artifactId>spring-boot-maven-plugin</artifactId>
    			</plugin>
    		</plugins>
    	</build>
    </project>
  3. Create the Java classes App.java, Employee.java and EmployeeController.java under com.javainterviewpoint folder.
  4. Now create a new folder “templates” under src/main/resources. Now place the index.html and employeeDetails.html under it.

The spring-boot-starter-parent is a special starter, it provides useful Maven defaults. Since we are developing a web application, we also need to add spring-boot-starter-web dependency.This will add dependencies such Tomcat, Jackson, Spring boot etc which are required for our application.

Other interesting articles which you may like …

  • Spring Boot JPA Tutorial
  • Spring Boot Tomcat JDBC Connection Pool
  • Spring Boot Logging – Logback
  • Spring Boot Log4j2 Example
  • Spring Boot HikariCP Connection Pool
  • Spring Boot JDBC Connection Pool
  • Spring Boot RESTful Web Services Example
  • Spring Boot Kotlin RESTful Web Services
  • Spring Boot with Kotlin Hello World Example
  • Spring Boot Hello World Example with Maven
  • Spring Boot Hello World Example in Eclipse
  • How to Create Deployable WAR | Spring Boot | SpringBootServletInitializer
  • Spring Boot Change Embedded Tomcat default port
  • Spring Boot CRUDRepository Example- Spring Data JPA
  • Fix missing src/main/java folder in Eclipse Maven Project
  • Spring MVC CRUD Example with MySql + JdbcTemplate
  • RESTful Java Client With Jersey Client
  • RESTEasy Hello World Example with Apache Tomcat
  • RESTful Java client with RESTEasy client
  • Spring RESTful Web Services Hello World XML Example
  • Springfox Swagger 2 for Spring RESTful Web Services

Spring Boot Thymeleaf Example

Dependency Tree

[INFO] ------------------------------------------------------------------------
[INFO] Building SpringBootThymeleaf 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO] 
[INFO] --- maven-dependency-plugin:2.10:tree (default-cli) @ SpringBootThymeleaf ---
[INFO] com.javainterviewpoint:SpringBootThymeleaf:jar:0.0.1-SNAPSHOT
[INFO] \- org.springframework.boot:spring-boot-starter-thymeleaf:jar:1.5.3.RELEASE:compile
[INFO]    +- org.springframework.boot:spring-boot-starter:jar:1.5.3.RELEASE:compile
[INFO]    |  +- org.springframework.boot:spring-boot:jar:1.5.3.RELEASE:compile
[INFO]    |  |  \- org.springframework:spring-context:jar:4.3.8.RELEASE:compile
[INFO]    |  +- org.springframework.boot:spring-boot-autoconfigure:jar:1.5.3.RELEASE:compile
[INFO]    |  +- org.springframework.boot:spring-boot-starter-logging:jar:1.5.3.RELEASE:compile
[INFO]    |  |  +- ch.qos.logback:logback-classic:jar:1.1.11:compile
[INFO]    |  |  |  \- ch.qos.logback:logback-core:jar:1.1.11:compile
[INFO]    |  |  +- org.slf4j:jcl-over-slf4j:jar:1.7.25:compile
[INFO]    |  |  +- org.slf4j:jul-to-slf4j:jar:1.7.25:compile
[INFO]    |  |  \- org.slf4j:log4j-over-slf4j:jar:1.7.25:compile
[INFO]    |  +- org.springframework:spring-core:jar:4.3.8.RELEASE:compile
[INFO]    |  \- org.yaml:snakeyaml:jar:1.17:runtime
[INFO]    +- org.springframework.boot:spring-boot-starter-web:jar:1.5.3.RELEASE:compile
[INFO]    |  +- org.springframework.boot:spring-boot-starter-tomcat:jar:1.5.3.RELEASE:compile
[INFO]    |  |  +- org.apache.tomcat.embed:tomcat-embed-core:jar:8.5.14:compile
[INFO]    |  |  +- org.apache.tomcat.embed:tomcat-embed-el:jar:8.5.14:compile
[INFO]    |  |  \- org.apache.tomcat.embed:tomcat-embed-websocket:jar:8.5.14:compile
[INFO]    |  +- org.hibernate:hibernate-validator:jar:5.3.5.Final:compile
[INFO]    |  |  +- javax.validation:validation-api:jar:1.1.0.Final:compile
[INFO]    |  |  +- org.jboss.logging:jboss-logging:jar:3.3.1.Final:compile
[INFO]    |  |  \- com.fasterxml:classmate:jar:1.3.3:compile
[INFO]    |  +- com.fasterxml.jackson.core:jackson-databind:jar:2.8.8:compile
[INFO]    |  |  +- com.fasterxml.jackson.core:jackson-annotations:jar:2.8.0:compile
[INFO]    |  |  \- com.fasterxml.jackson.core:jackson-core:jar:2.8.8:compile
[INFO]    |  +- org.springframework:spring-web:jar:4.3.8.RELEASE:compile
[INFO]    |  |  +- org.springframework:spring-aop:jar:4.3.8.RELEASE:compile
[INFO]    |  |  \- org.springframework:spring-beans:jar:4.3.8.RELEASE:compile
[INFO]    |  \- org.springframework:spring-webmvc:jar:4.3.8.RELEASE:compile
[INFO]    |     \- org.springframework:spring-expression:jar:4.3.8.RELEASE:compile
[INFO]    +- org.thymeleaf:thymeleaf-spring4:jar:2.1.5.RELEASE:compile
[INFO]    |  +- org.thymeleaf:thymeleaf:jar:2.1.5.RELEASE:compile
[INFO]    |  |  +- ognl:ognl:jar:3.0.8:compile
[INFO]    |  |  +- org.javassist:javassist:jar:3.21.0-GA:compile
[INFO]    |  |  \- org.unbescape:unbescape:jar:1.1.0.RELEASE:compile
[INFO]    |  \- org.slf4j:slf4j-api:jar:1.7.25:compile
[INFO]    \- nz.net.ultraq.thymeleaf:thymeleaf-layout-dialect:jar:1.4.0:compile
[INFO]       \- org.codehaus.groovy:groovy:jar:2.4.10:compile

index.html

All our templates are placed under src/main/resources/templates directory

<html lang="en">  
    <head>  
        <title>Spring Boot Thymeleaf Example</title>  
    </head>  
    <body>  
        <form action="display" method="post">  
        	<h1>Employee Details Forms</h1>
            <table>  
                <tr>  
                    <td><label for="Name">Name</label></td>  
                    <td><input type="text" name="name"></input></td>  
                </tr>  
                <tr>  
                    <td><label for="Age">Age</label></td>  
                    <td><input type="text" name="age"></input></td>  
                </tr>  
                <tr>  
                    <td></td>  
                    <td><input type="submit" value="Submit"></input></td>  
                </tr>  
            </table>  
        </form>  
    </body>  
</html>

employeeDetails.html

<html xmlns:th="http://thymeleaf.org">
<head>
<meta charset="UTF-8" />
<title>Display Employee Details</title>
</head>
<body>
	<table border="1">
		<tr>
			<th>Name</th>
			<th>Age</th>
		</tr>
		<tr th:each="employee : ${employeeList}">
			<td th:text="${employee.name}">Name</td>
			<td th:text="${employee.age}">Age</td>
		</tr>
	</table>
    <strong><a href="/">Click here to go back</a></strong>
</body>
</html>
  • In the first line we are setting the XML Namespace for Thymeleaf
  • Thymeleaf th:each will enable us to iterate a collection, we will be iterating each employee object in the employeeList
<tr th:each="employee : ${employeeList}">
  • Using th:text we can access the individual values name and age.
<td th:text="${employee.name}">Name</td> 

<td th:text="${employee.age}">Age</td>

EmployeeController.java

package com.javainterviewpoint;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Controller;
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;

@Controller
public class EmployeeController
{
    private static List employeeList = new ArrayList();
    
    @RequestMapping("/")
    public String home()
    {
        return "index";
    }

    @RequestMapping(value = "/display", method = RequestMethod.POST)
    public ModelAndView saveEmployee(@ModelAttribute Employee employee)
    {
        ModelAndView mav = new ModelAndView();
        mav.setViewName("employeeDetails");
        employeeList.add(employee);
        mav.addObject("employeeList", employeeList);
        return mav;
    }
}
  • We have created our EmployeeController under com.javainterviewpoint package
  • We have 2 methods in the controller
    • home() – This method will redirect the user to index template page.
    • saveEmployee() – This method will add the employee object to the employeeList and will be redirected to the employeeDetails template page.

Employee.java

Employee Class is a simple POJO consisting of the getters and setters for the properties name and age.

package com.javainterviewpoint;

public class Employee {  
    String name;  
    String age;
    public String getName()
    {
        return name;
    }
    public void setName(String name)
    {
        this.name = name;
    }
    public String getAge()
    {
        return age;
    }
    public void setAge(String age)
    {
        this.age = age;
    }
}

App.java

package com.javainterviewpoint;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class App {

    public static void main(String[] args) throws Exception {
        SpringApplication.run(App.class, args);
    }

}
  • @SpringBootApplication annotation does the work of @EnableAutoConfiguration, @Configuration and @ComponentScan annotations together

Output:

Select the Project –>Run As –> Run Configuration –>Maven –> New. In the Main tab, key in the Goals as “spring-boot:run” and click on Run.

Spring Boot Thymeleaf Example 1

Spring Boot Thymeleaf Example 2

Filed Under: J2EE, Java, Spring, Spring Boot Tagged With: Spring Boot, Spring Boot Thymeleaf, Spring Boot Thymeleaf Example, Thymeleaf

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Java Basics

  • JVM Architecture
  • Object in Java
  • Class in Java
  • How to Set Classpath for Java in Windows
  • Components of JDK
  • Decompiling a class file
  • Use of Class.forName in java
  • Use Class.forName in SQL JDBC

Oops Concepts

  • Inheritance in Java
  • Types of Inheritance in Java
  • Single Inheritance in Java
  • Multiple Inheritance in Java
  • Multilevel Inheritance in Java
  • Hierarchical Inheritance in Java
  • Hybrid Inheritance in Java
  • Polymorphism in Java – Method Overloading and Overriding
  • Types of Polymorphism in java
  • Method Overriding in Java
  • Can we Overload static methods in Java
  • Can we Override static methods in Java
  • Java Constructor Overloading
  • Java Method Overloading Example
  • Encapsulation in Java with Example
  • Constructor in Java
  • Constructor in an Interface?
  • Parameterized Constructor in Java
  • Constructor Chaining with example
  • What is the use of a Private Constructors in Java
  • Interface in Java
  • What is Marker Interface
  • Abstract Class in Java

Java Keywords

  • Java this keyword
  • Java super keyword
  • Final Keyword in Java
  • static Keyword in Java
  • Static Import
  • Transient Keyword

Miscellaneous

  • newInstance() method
  • How does Hashmap works internally in Java
  • Java Ternary operator
  • How System.out.println() really work?
  • Autoboxing and Unboxing Examples
  • Serialization and Deserialization in Java with Example
  • Generate SerialVersionUID in Java
  • How to make a class Immutable in Java
  • Differences betwen HashMap and Hashtable
  • Difference between Enumeration and Iterator ?
  • Difference between fail-fast and fail-safe Iterator
  • Difference Between Interface and Abstract Class in Java
  • Difference between equals() and ==
  • Sort Objects in a ArrayList using Java Comparable Interface
  • Sort Objects in a ArrayList using Java Comparator

Follow

  • Coding Utils

Useful Links

  • Spring 4.1.x Documentation
  • Spring 3.2.x Documentation
  • Spring 2.5.x Documentation
  • Java 6 API
  • Java 7 API
  • Java 8 API
  • Java EE 5 Tutorial
  • Java EE 6 Tutorial
  • Java EE 7 Tutorial
  • Maven Repository
  • Hibernate ORM

About JavaInterviewPoint

javainterviewpoint.com is a tech blog dedicated to all Java/J2EE developers and Web Developers. We publish useful tutorials on Java, J2EE and all latest frameworks.

All examples and tutorials posted here are very well tested in our development environment.

Connect with us on Facebook | Privacy Policy | Sitemap

Copyright ©2023 · Java Interview Point - All Rights Are Reserved ·