Guide to Spring Boot Thymeleaf

In this post, we will discuss how to set up and use Thymeleaf for Spring Boot application. This post aims to work as a guide for Spring Boot Thymeleaf configurations.

 

Introduction

Traditionally, Java Server Pages are known as the default choice for generating HTML while building Spring MVC applications.JSP is a mature technology and provides a number of benefits, however, there are a number of things which we should keep in mind

  • JSP is not a templating engine. These files compiled to the servlet before served as web content.
  • Thymeleaf is a true templating engine which takes the HTML file, parses it and then produces web content which is being served.
  • Thymeleaf is more like an HTML-ish view when you compare it with JSP views.
  • It allows using templates as prototypes, meaning they may be viewed as static files.

Spring Boot provides auto-configuration to support Thymeleaf.

 

1. Spring Boot Thymeleaf

Let’s take a look at the steps required to use Thymeleaf in our application.

 

1.1. Maven Setup

Spring Boot will provide auto-configuration for Thymeleaf.Add spring-boot-starter-thymeleaf dependency in pom.xml to enable this auto-configuration.

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

No other configurations required, Spring Boot will inject all required configuration to start working with Thymeleaf.

 

1.2. Thymeleaf  Template

We may place our HTML templates at the following location src/main/resources/templates. Our template will be automatically picked by Spring Boot. Let’s create a sample HTML template(greeting.html) based on Thymeleaf.

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body>
<div class="container">
    <div class="hero-unit">
        <h1><p th:text="'Hello, ' + ${name} + '!'" /></h1>
        <p>
            Welcome to the Spring Boot Thymeleaf example post
            Get started quickly by signing up.
        </p>
        <p>
            <a href="/signup" th:href="@{/signup}" class="btn btn-large btn-success">Sign up</a>
        </p>
    </div>
    <div th:replace="fragments/footer :: footer">&copy; 2018 Java Development Journal</div>
</div>
</body>
</html>

Let’s take a closer look at our greeting.html template.

  • The first line is the standard HTML 5 declaration tag.
  • Second line XML namespace for Thymeleaf.
  • <meta> tag define character encoding.

In our example, will print a standard hello message and evaluates the th:text expression to render the value of the ${name} parameter set in the controller.

 

1.3. Customize Template Directory 

By default Spring Boot setup default configuration for our application including picking up HTML templates automatically from the src/main/resources/templates location.We have the flexibility to change this.

Set spring.thymeleaf.template-resolver-order=0 in the application.properties file.As part of the next step create custom ClassLoaderTemplateResolver

@Configuration
public class CustomConfig implements WebMvcConfigurer {

    @Bean
    public ClassLoaderTemplateResolver yourTemplateResolver() {
        ClassLoaderTemplateResolver configurer = new ClassLoaderTemplateResolver();
        configurer.setPrefix("customLocation/");
        configurer.setSuffix(".html");
        configurer.setTemplateMode(TemplateMode.HTML);
        configurer.setCharacterEncoding("UTF-8");
        configurer.setOrder(0);  // this is important. This way spring //boot will listen to both places 0 and 1
        configurer.setCheckExistence(true    return configurer;
    }
}

 

1.4. Spring MVC Controller

In this step, we will create a Spring MVC Controller, our controller will perform the following tasks

  • Handle a GET request for /greeting URL mapping.
  • Return a view of the name “greeting“.Spring Boot view resolver will load HTML template from the following location src/main/resources/templates/greeting.
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class GreetingController {

    @GetMapping("/greeting")
    public String greeting(@RequestParam(name="name", required=false, defaultValue="World") String name, Model model) {
        model.addAttribute("name";
        return "greeting";
    }

}

 

1.5. Running Application

package com.javadevjournal;

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

@SpringBootApplication
public class JavadevjournalThymeleafExampleApplication {

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

Spring Boot Thymeleaf

Summary

In this post, we covered how to set up and use Thymeleaf for your Spring Boot application. We covered different Spring Boot Thymeleaf configurations and how to customize the Thymeleaf behavior.

Umesh

Hello!! I am Umesh- an engineer by profession and a photographer by passion.I like to build stuff on the web using OSS and love to capture the world through my lens.

follow me on:

3
Leave a Reply

avatar
2 Comment threads
1 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
2 Comment authors
Umesh AwasthiDirk Schumacher Recent comment authors

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

  Subscribe  
newest oldest most voted
Notify of
Dirk Schumacher
Guest
Dirk Schumacher

The line in greeting.html’s ..div th:replace=”fragments/footer :: footer” … © 2018 Java Development Journal…/div… breaks.
Removing it helps.

Umesh Awasthi
Admin
Umesh Awasthi

Hello Dirk,

Have you tried to run the example available on the GitHub repo (https://github.com/umeshawasthi/javadevjournal/tree/master/Spring-Boot/javadevjournal-thymeleaf-example)? I checked and it is working as expected. Let me know if you are still facing the same issue.

trackback
Spring MVC @ModelAttribute Annotation | Java Development Journal

[…] basic example to help you understand the above workflow. We are creating a simple HTML form using Thymeleaf. Let’s take a look at the example first before we get into more […]