Tymeleaf template engine of SpringBoot

According to the notes of studying java in B station

Template engine Thymeleaf

The front end wants to display data. We used to convert pages into JSPS. In this way, we can realize data display and interaction. jsp supports very powerful functions, including the ability to write Java code. But we use the spring boot project in jar mode instead of war. We still use embedded Tomcat, but now spring boot does not support jsp by default. What should I use?

SpringBoot recommends that you use the template engine:

Template engine, we have heard a lot. In fact, jsp is a template engine. There are many freemakers, including the tymeleaf recommended by SpringBoot. There are many template engines, but their ideas are the same. What kind of ideas can we see in this picture

The role of the template engine is to use expressions to parse the background data.

Introducing Thymeleaf

How to introduce it? For springboot, everything is not a start. Let's introduce it into the project. Here are three websites:

Official website of Thymeleaf: https://www.thymeleaf.org/

Tymeleaf's homepage at Github: https://github.com/thymeleaf/thymeleaf

Official Spring document: find our corresponding version


Find the corresponding pom dependency: you can enter the source code appropriately to see the original package!

Official website jar package

Tymeleaf analysis

Previously, we have introduced Thymeleaf. How to use this?

First of all, we need to follow the automatic configuration principle of spring boot to see our automatic configuration rule of Thymeleaf. According to that rule, we will use it.

Let's go to the automatic configuration class of Thymeleaf: ThymeleafProperties

@ConfigurationProperties(prefix = "spring.thymeleaf")
public class ThymeleafProperties {

	private static final Charset DEFAULT_ENCODING = StandardCharsets.UTF_8;

	public static final String DEFAULT_PREFIX = "classpath:/templates/";

	public static final String DEFAULT_SUFFIX = ".html";

We can see the default prefix and suffix in it!

We just need to put our html page under the templates under the classpath, and thmeleaf can help us render automatically.

You don't need to configure anything to use thmeleaf, just put it in the specified folder!


First write a TestController

public class TestController {
    public String test1(){
        //Auto resolve to classpath:/templates/test.html
        return "test";

Set up in template test.html

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <title>thymeleaf Test page</title>
//I'm in

Run tests:

Thmeleaf syntax

To learn grammar, it's better to refer to the official website documents. Let's find the corresponding version;

Official website of Thymeleaf: https://www.thymeleaf.org/ Take a look at the official website! Let's download the official documents of tymeleaf!

Let's do the simplest exercise: we need to find out some data and show it on the page

1. Modify test request and add data transmission

public class TestController {
    public String test1(Model model){
        //Auto resolve to classpath:/templates/test.html
        model.addAttribute("msg","hello Thymeleaf!");
        return "test";

2. We need to import namespace constraints first

We can go to the official document ා 3 to see the namespace

<html lang="en"  xmlns:th="http://www.thymeleaf.org">

3. Write page

<!DOCTYPE html>
<html lang="en"  xmlns:th="http://www.thymeleaf.org">
    <meta charset="UTF-8">
    <title>thymeleaf Test page</title>
//I'm in
<div th:text="${msg}"></div>

4. Test:

Usage syntax of Thymeleaf

1. We can use any th:attr to replace the value of the native attribute in Html!
2. Expression

Simple expressions:(Expression syntax)
Variable Expressions: ${...}: Get the variable value; OGNL;
    1),Get object properties, call methods
    2),Use built-in base objects:#18
         #ctx : the context object.
         #vars: the context variables.
         #locale : the context locale.
         #request : (only in Web Contexts) the HttpServletRequest object.
         #response : (only in Web Contexts) the HttpServletResponse object.
         #session : (only in Web Contexts) the HttpSession object.
         #servletContext : (only in Web Contexts) the ServletContext object.

    3),Some built-in tool objects:
      #execInfo : information about the template being processed.
      #uris : methods for escaping parts of URLs/URIs
      #conversions : methods for executing the configured conversion service (if any).
      #dates : methods for java.util.Date objects: formatting, component extraction, etc.
      #calendars : analogous to #dates , but for java.util.Calendar objects.
      #numbers : methods for formatting numeric objects.
      #strings : methods for String objects: contains, startsWith, prepending/appending, etc.
      #objects : methods for objects in general.
      #bools : methods for boolean evaluation.
      #arrays : methods for arrays.
      #lists : methods for lists.
      #sets : methods for sets.
      #maps : methods for maps.
      #aggregates : methods for creating aggregates on arrays or collections.

  Selection Variable Expressions: *{...}: Select expressions: and ${}It is the same in function;
  Message Expressions: #{...}: get international content
  Link URL Expressions: @{...}: definition URL;
  Fragment Expressions: ~{...}: Fragment reference expression

      Text literals: 'one text' , 'Another one!' ,...
      Number literals: 0 , 34 , 3.0 , 12.3 ,...
      Boolean literals: true , false
      Null literal: null
      Literal tokens: one , sometext , main ,...
Text operations:(Text operation)
    String concatenation: +
    Literal substitutions: |The name is ${name}|
Arithmetic operations:(***
    Binary operators: + , - , * , / , %
    Minus sign (unary operator): -
Boolean operations:(Boolean operation)
    Binary operators: and , or
    Boolean negation (unary operator): ! , not
Comparisons and equality:(Comparison operation)
    Comparators: > , < , >= , <= ( gt , lt , ge , le )
    Equality operators: == , != ( eq , ne )
Conditional operators:Conditional operation (ternary operator)
    If-then: (if) ? (then)
    If-then-else: (if) ? (then) : (else)
    Default: (value) ?: (defaultvalue)
Special tokens:
    No-Operation: _


Write controller

public class TestController2 {
    public String test2(Map<String,Object> map){
        map.put("users", Arrays.asList("qi","wuxin"));
        return "test";

Test page

<!DOCTYPE html>
<html lang="en"  xmlns:th="http://www.thymeleaf.org">
    <meta charset="UTF-8">
    <title>thymeleaf Test page</title>
I'm in
<div th:text="${msg}"></div>
    <!--No escape-->
<div th:utext="${msg}"></div>
<h4 th:each="user: ${users}" th:text="${user}"></h4>
<!--In line writing-->
<h4 th:each="user: ${users}">[[${user}]]</h4>

Results page

Tags: Java Thymeleaf Spring JSP

Posted on Tue, 02 Jun 2020 21:52:29 -0400 by dlf