SpringBoot 2. X basic tutorial: integrating Thymeleaf with SpringBoot

Posted by imcomguy on Wed, 29 Sep 2021 05:17:05 +0200

Micro signal: hzy1014211086. If you are learning Spring Boot, you can join our Spring technology exchange group and grow together

For Web projects, the front-end and back-end separation mode is the most popular. At present, the front-end framework is very perfect, and the front-end and back-end separation scheme is also very mature. The separation of front end and back end can help the development team of Web products better split tasks and make developers focus more on the development technology at one end. However, as far as I know, the front and back ends of the management background of a small number of small and medium-sized companies are not separated, and in the development of front and back ends, we will need to use Thymeleaf.

Next, let's talk about how to use Thymeleaf template engine to develop the application of Web page class in Spring Boot application.

1, Static file

When using Spring Boot to develop a complete system, we often need to use the front-end page, which indispensable needs to access static resources, such as images, css, js and other files.

Spring Boot uses various configuration properties in webmvcoautoconfiguration, and provides us with static resource processing by default. If special treatment is required, it can be modified through configuration.

The location of the static resource directory provided by the SpringBoot framework by default needs to be placed under the classpath, and the naming specification is required. The naming specification for the directory name is as follows:

  • /static
  • /public
  • /resources
  • /META-INF/resources

Two. Template engine

In addition to REST web services, you can also use spring MVC to serve dynamic HTML content. Spring MVC supports a variety of template technologies, including Thymeleaf, FreeMarker and JSP. Of course, many other template engines also have their own spring MVC integration.

Spring Boot supports a variety of template engines, including:

  • FreeMarker
  • Groovy
  • Thymeleaf (official recommendation)
  • Mustache

The JSP technology Spring Boot is officially not recommended for four reasons:

  • tomcat only supports the packaging of war, not executable jar s.
  • Jetty nested containers do not support JSPS.
  • Undertow does not support JSP S.
  • Creating a custom error.jsp page does not override the default view of error handling, but should use a custom error page

When you use any of the above template engines, their default template configuration path is src/main/resources/templates. Of course, you can also modify this path. How to modify it can be queried and modified in the configuration properties of subsequent template engines.

3, Thymeleaf template engine

Thymeleaf is a template engine for rendering XML/XHTML/HTML5 content. It is a modern server-side Java template engine suitable for Web and independent environment. It is similar to Velocity and FreeMarker template engines, which can completely replace JSP. Compared with other template engines, it has the following three characteristics:

  • Thymeleaf can run in both network and non network environments, that is, it allows artists to view the static effect of the page in the browser and programmers to view the dynamic page effect with data in the server. This is because it supports html prototypes, and then adds additional attributes in html tags to achieve the presentation of template + data. When the browser interprets html, it ignores undefined tag attributes, so thymeleaf's template can run statically; When data is returned to the page, the thymeleaf tag will dynamically replace the static content to make the page display dynamically.
  • Thymeleaf's out of the box features. It provides standard and Spring standard dialects, which can directly apply templates to achieve JSTL and OGNL expression effects, so as to avoid the trouble of setting templates, changing JSTL and changing labels every day. At the same time, developers can also extend and create custom dialects.
  • Thymeleaf provides Spring standard dialect and an optional module perfectly integrated with Spring MVC, which can quickly realize form binding, Attribute Editor, internationalization and other functions.

4, Introduce dependency


5, Write controller

In the previous articles, we all used @ RestController to process requests. The returned content is JSON objects. How do we implement it if we need to render html pages?

public class TestController {

   * Scheme I
   * @param model
   * @return
  public String index(Model model) {
    model.addAttribute("id", "1");
    model.addAttribute("title", "SpringBoot Thymeleaf");
    model.addAttribute("author", "Java Procedural fish");
    return "index1";

   * Scheme II
   * @return
  public Object index2() {
    ModelAndView modelAndView = new ModelAndView("/index2");

    modelAndView.addObject("id", "2");
    modelAndView.addObject("title", "SpringBoot Thymeleaf2");
    modelAndView.addObject("author", "Java Procedural fish");
    return modelAndView;

   * Programme III
   * @param modelMap
   * @return
  public String index3(ModelMap modelMap) {
    modelMap.addAttribute("id", "3");
    modelMap.addAttribute("title", "SpringBoot Thymeleaf3");
    modelMap.addAttribute("author", "Java Procedural fish");
    return "index3";

6, Write html

Create index1.html, index2.html and index3.html files under src/main/resources/templates with the same code.

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <th th:text="${id}">id</th>
    <th th:text="${title}">title</th>
    <th th:text="${author}">author</th>

7, Grammar


Thymeleaf uses th:each for loop traversal

public class BlogController {

  public String each(Model model) {
    ArrayList<Blog> list = new ArrayList<>();
    list.add(new Blog(1, "each1", "java Program fish 1"));
    list.add(new Blog(2, "each2", "java Procedural fish 2"));
    list.add(new Blog(3, "each3", "java Procedural fish 3"));

    model.addAttribute("list", list);
    return "each";


	    <tr th:each="item:${list}">
	        <td th:text="${item.id}"></td>
	        <td th:text="${item.title}"></td>
	        <td th:text="${item.author}"></td>


Thymeleaf uses th:if and th:unless attributes for condition judgment. th:if is the content displayed when the condition in the expression is true, and th:unless is the content displayed only when the condition in the expression is not true.

public class BlogController {
  public String ifHtml(Model model) {
    model.addAttribute("id", 1);
    return "if";


    <div th:if="${id == 1}">th:if id==1</div>
    <div th:if="${id != 1}">th:if id!=1</div>

    <div th:unless="${id == 1}">th:unless id==1</div>
    <div th:unless="${id != 1}">th:unless id!=1</div>


th:include, layout label, replace content to imported file
th:replace, layout the label, and replace the entire label to the imported file

In our development, we need to extract the common parts, such as the head and bottom of the article, make the head and bottom of the article into separate pages, and then let other pages include the head and bottom. This is code reuse thinking.


<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
    <meta charset="UTF-8">
    <title>Thymeleaf include</title>
    <!--  Syntax description  "::"The template file name is preceded by the selector -->
    <div class="commonHead" th:replace="commonHead::commonHead"></div>
    Blog body
    <div class="commonFooter" th:replace="commonFooter::commonFooter"></div>


<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
    <meta charset="UTF-8">
    <title>General code-bottom</title>
    <div class="commonFooter" th:fragment="commonFooter">
        Bottom of Blog


<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
    <meta charset="UTF-8">
    <title>General code-head</title>
    <div class="commonHead" th:fragment="commonHead">
        Blog head

8, Default parameter configuration for Thymeleaf

thymeleaf template parser properties can be configured in application.properties

# THYMELEAF (ThymeleafAutoConfiguration)
#Enable template caching (default: true)
#Check that the template exists before rendering it.
#Check whether the template location is correct (default: true)
#Value of content type (default: text/html)
#Enable MVC Thymeleaf view resolution (default: true)
#Template code
#A comma separated list of view names to be excluded from resolution
#The template pattern to be applied to the template. See also standardtemplate modehandlers (default: HTML5)
#Prefix added to the view name when building the URL (default: classpath:/templates /)
#Suffix added to the view name when building the URL (default:. html)
#The order of the Thymeleaf template parser in the parser chain. By default, it comes first. The order starts from 1. This property needs to be set only when additional templateresolver beans are defined.
#A comma separated list of resolvable view names

More page syntax of Thymeleaf can be accessed Official documents of Thymeleaf To further study and use.

9, Source code

For relevant examples in this article, you can view the chapter3 directory in the following warehouse:

  • Gitee: https://gitee.com/hezhiyuan007/spring-boot-study
  • Github: https://github.com/java-fish-0907/spring-boot-study

Topics: Spring Spring Boot