How to Integrate Spring Boot with Thymeleaf: A Step-by-Step Guide
Spring framework is one of the leading frameworks in the JAVA world and developers across the globe utilize it for developing reliable and high-quality Enterprise-level applications. Of late, developers have also started using the alternative form of Spring framework popularly termed as Spring Boot.
This blog post will take you through a series of steps each designed in a way to help you understand how to integrate Spring Boot with Thymeleaf. However, before we begin, we do need to understand a little about Spring Boot and Thymeleaf too.
What is the Spring Boot Framework?
The Spring Boot framework came into existence to resolve bootstrapping issues and design new applications. It provides a default set of codes and configuration steps which makes it easier for the developers to integrate it into their applications.
The framework operates on the “Opinionated Defaults Configuration” approach and boasts three major aspects of any application development process:
- Development
- Unit Testing
- Integration Testing
What is Thymeleaf?
Thymeleaf is a simple Java-based template which allows you to create both web and standalone applications. By default, Thymeleaf comes with 6 templates namely:
- XML
- Valid XML
- XHTML
- Valid XHTML
- HTML5
- Legacy HTML5
Additionally, developers also consider Thymeleaf ideal for HTML5 JVM web development because it gives them the flexibility to customize the code based on their project requirements and because it supports a good range of Spring frameworks and additional tools.
Integrating Spring Boot with Thymeleaf – A Step Guide
With the basics in place, it is time to begin with our next segment which details the actual integration process in a step-wise manner. You can integrate both in multiple ways, however, for the sake of convenience, we will walk you through a manual JAVA configuration to set up Thymeleaf with Spring Boot.
Checking Pre-requisite Tools and Software
Your system must have the following tools and software installed before you start with the integration process:
- JAVA 8
- Spring Boot
- Thymeleaf v3.0
- Maven v3.3
- Eclipse
Project Structure
Once you have executed all the steps carefully, your basic project structure should look something like the following:
pom.xml
src
├───main
│ ├───java
│ │ └───com
│ │ └───zetcode
│ │ │ Application.java
│ │ └───config
│ │ WebConfig.java
│ └───resources
│ └───my templates
│ index.html
└───test
└───java
Note: Thymeleaf stores all its template files in the following custom directory: src/main/resources/mytemplates while its default template directory is: src/main/resources/templates.
Working Out the Basic Installation
Spring Boot uses JAVA SDK v1.8 or higher by default to run smoothly. To check which version of JAVA is installed on your system, you need to run the following code on your DOS prompt:
$ java –version
java version “1.8.0_102” Java(TM) SE Runtime Environment (build 1.8.0_102-b14) Java HotSpot(TM) 64-Bit Server VM (build 25.102-b14, mixed mode) |
- If you see a similar output on your DOS prompt you do have JAVA installed. In case, nothing appears, proceed to the given link to install JDK and set up the PATH Environment variable on your system.
- As Eclipse is also a mandate, you need to download the latest build and install Eclipse on your system based on your operating system. Once it’s done, execute the Eclipse.exe file.
- Next, you can install Maven in two ways:
- Within the Eclipse IDE: The steps are as follows:
- Open your Eclipse IDE and click HELP >> Install New Software
- Click on the ADD button to add a new repository
- In the popup box, fill out the:
- Name: M2Eclipse
- Location: http://download.eclipse.org/technology/m2e/releases
- Once done, select all the plugins and click on NEXT
- Accept the terms and conditions of the agreement and click Finish
- Once the process is complete, you will be asked to restart Eclipse IDE. Click on YES to restart the IDE.
- Installing Maven using the PATH variable: In this process, you need to add the bin folder with the mvn command to the PATH variable. Follow the installation guide here: Installing Maven through PATH
Next, run the following command to check for Maven installation:
$ mvn –v
Apache Maven 3.5.4 (1edded0938998edf8bf061f1ceb3cfdeccf443fe; 2018-06-17T14:33:14-04:00) Maven home: /usr/local/Cellar/maven/3.3.9/libexec Java version: 1.8.0_102, vendor: Oracle Corporation |
Once both Eclipse and Maven are installed, move onto the next section and check for the dependencies required to integrate Thymeleaf with Spring Boot.
Integrating Thymeleaf with Spring Boot – The Actual Process
- To integrate Thymeleaf with Spring Boot, we first need to execute the following Maven dependency:
<dependency>
<groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> |
- Since, we are using Thymeleaf v3.0 in this guide, we also need to configure the following two properties in the “pom.xml” file:
- thymeleaf.version
- thymeleaf-layout-dialect.version
<properties>
<thymeleaf.version>3.0.6.RELEASE</thymeleaf.version> <thymeleaf-layout-dialect.version>2.2.2</thymeleaf-layout-dialect.version> <java.version>1.8</java.version> </properties> |
- In this step, we would create our “pom.xml” file. To create, open any text editor of your choice like say “Notepad++” and add the following code to it. Once done, save the file under the name “pom.xml” which you can later use to build up your project.
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd”> <modelVersion>4.0.0</modelVersion> <groupId>com.zetcode</groupId> <artifactId>thymeleafconfigex</artifactId> <version>1.0-SNAPSHOT</version> <packaging>jar</packaging> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>11</maven.compiler.source> <maven.compiler.target>11</maven.compiler.target> </properties> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.0.RELEASE</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <optional>true</optional> </dependency> <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> |
- Once you have created the “pom.xml” file, you need to configure Thymeleaf using the “WebConfig.java” file and set up a ‘view’ and ‘controller’ for the homepage.
Use the following programming code to achieve the stated task:
package com.zetcode.config;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Description; import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.thymeleaf.spring5.SpringTemplateEngine; import org.thymeleaf.spring5.view.ThymeleafViewResolver; import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver; @Configuration public class WebConfig implements WebMvcConfigurer { @Bean @Description(“Thymeleaf template resolver serving HTML 5”) public ClassLoaderTemplateResolver templateResolver() { var templateResolver = new ClassLoaderTemplateResolver(); templateResolver.setPrefix(“mytemplates/”); templateResolver.setCacheable(false); templateResolver.setSuffix(“.html”); templateResolver.setTemplateMode(“HTML5”); templateResolver.setCharacterEncoding(“UTF-8”); return templateResolver; } @Bean @Description(“Thymeleaf template engine with Spring integration”) public SpringTemplateEngine templateEngine() { var templateEngine = new SpringTemplateEngine(); templateEngine.setTemplateResolver(templateResolver()); return templateEngine; } @Bean @Description(“Thymeleaf view resolver”) public ViewResolver viewResolver() { var viewResolver = new ThymeleafViewResolver(); viewResolver.setTemplateEngine(templateEngine()); viewResolver.setCharacterEncoding(“UTF-8”); return viewResolver; } @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController(“/”).setViewName(“index”); } } |
- We also need to define a dedicated template resolver which would help us resolve various templates into different “TemplateResolution” objects.
You can call up the templates located on your CLASSPATH using “ClassLoaderTemplateResolver” method.
@Bean
@Description(“Thymeleaf template resolver serving HTML 5”) public ClassLoaderTemplateResolver templateResolver() { |
Note: To serve HTML5 content, you can execute the following code:
templateResolver.setTemplateMode(“HTML5”); |
- The following code will help you create a Thymeleaf template engine with Spring integration:
@Bean
@Description(“Thymeleaf template engine with Spring integration”) public SpringTemplateEngine templateEngine() {
var templateEngine = new SpringTemplateEngine(); templateEngine.setTemplateResolver(templateResolver()); return templateEngine; } |
- In case you need to display the current date, change the “resources/templates/index.html” file with the following code:
<!DOCTYPE html>
<html xmlns:th=”http://www.thymeleaf.org”> <head> <title>Home page</title> <meta charset=”UTF-8″/> <meta name=”viewport” content=”width=device-width, initial-scale=1.0″/> </head> <body> <p> <span th:text=”‘Today is: ‘ + ${#dates.format(#dates.createNow(), ‘dd MMM yyyy HH:mm’)}” th:remove=”tag”></span> </p> </body> </html> |
- To set up the Spring Boot application for execution, you need to edit the “com/zetcode/Application.java” file with the following code:
package com.zetcode;
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } |
Executing the Code
With all the files edited successfully, execute your application using the following code:
$ mvn spring-boot:run |
Once executed your output should look similar to the following:
$ curl localhost:8080
<!DOCTYPE html> <html> <head> <title>Home page</title> <meta charset=”UTF-8″> <meta name=”viewport” content=”width=device-width, initial-scale=1.0″> </head> <body> <p> Today is: 08 Sep 2019 02:01 </p> </body> |
If you do see a similar output, that means you have successfully integrated Spring Boot into Thymeleaf.
Note: You can exit the application using the following key combination: CTRL + C
We hope you will find this step-by-guide to Spring Boot integration with Thymeleaf helpful. Do comment below and let us know how it turned out for you!
About Author: Johnny Morgan Technical writer with a keen interest in new technology and innovation areas. He focuses on web architecture, web technologies, Java/J2EE, open-source, WebRTC, big data and CRM. He is also associated with Aegis Infoways which offers Java Programmers India .
References
- https://www.journaldev.com/7969/spring-boot-tutorial
- https://spring.io/guides/gs/spring-boot/
- https://www.tutorialspoint.com/spring_boot/spring_boot_thymeleaf.htm
- https://www.thymeleaf.org/documentation.html
- http://zetcode.com/articles/springbootthymeleafconf/
- https://docs.oracle.com/javase/9/install/installation-jdk-and-jre-microsoft-windows-platforms.htm#JSJIG-GUID-2B9D2A17-176B-4BC8-AE2D-FD884161C958
- https://www.eclipse.org/downloads/
- https://www.ntu.edu.sg/home/ehchua/programming/howto/EclipseJava_HowTo.html
- https://maven.apache.org/install.html
- https://www.concretepage.com/spring-boot/spring-boot-thymeleaf-maven-example#complete
- https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/
- https://www.lifewire.com/how-to-open-command-prompt-2618089
- http://roufid.com/how-to-install-maven-on-eclipse-ide/