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 several benefits, however, there are several 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 it may view them as static files.

Spring Boot provides auto-configuration to support Thymeleaf.

 

1. Spring Boot Thymeleaf

Let’s 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 work 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 inspect 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 tests 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.

2 thoughts on “Guide to Spring Boot Thymeleaf”

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

Comments are closed.