I. Introduction to Thymeleaf

Thymeleaf is a Java XML/XHTML/HTML5 template engine that can be used in both Web and non-Web environments. It is better suited to provide XHTML/HTML5 in the view layer of mVC-based Web applications, but it can process any XML file even in an offline environment. It provides full Spring Framework integration.

I don’t see any specifics on Spring’s recommendation of Thymeleaf, except that JSP and Thymeleaf compare JSP to JSP, and Thymeleaf is a proxy for other templating engines.

In addition to ease of use, a vibrant community, and a healthy and rapid growth of a great template engine, performance is very important. How does Thymeleaf 3 compare to FreeMaker’s performance?

Two, Thymeleaf basic use

The use of Thymeleaf consists of two parts: tag + expression, tag is the syntax structure of Thymeleaf, and expression is the content realization in the syntax.

Through tag + expression, let the data and template combination, and finally converted into HTML code, returned to the user.

The basic use of Thymeleaf is divided into three parts:

  1. Label use
  2. Expression usage
  3. Set IDEA to complete Thymeleaf code

1. Label usage

1.1 TH :text Displays basic information

HTML code:

<! DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"< p style = "max-width: 100%; clear: both; min-height: 1em"${name}"></span>
</body>
</html>
Copy the code

Java code:

@RequestMapping("/")
public ModelAndView index() {
    ModelAndView modelAndView = new ModelAndView("/index");
    modelAndView.addObject("name"."Wang");
    return modelAndView;
}
Copy the code

End result: Lao Wang

1.2 TH: UText HTML content output

Use “th:text” to output the content as-is, use “th: UText “to output HTML tags.

Java code:

@RequestMapping("/eat")
public ModelAndView eat() {
    ModelAndView modelAndView = new ModelAndView("/cat");
    modelAndView.addObject("data". );
    return modelAndView;
}
Copy the code

HTML code:

<h4 th:text="'th:text '+${data}"></h4>
<h4 th:utext="'th:utext '+${data}"></h4>
Copy the code

Display effect:

1.3 th:if, th:unless

<span th:if="${age > 18}"<span style = "max-width: 100%; clear: both; min-height: 1em"${age > 18}"< p style = "max-width: 100%; clear: both; min-height: 1em;Copy the code

Th :if is the business process that meets the condition, th:unless is the opposite, which means remove.

1.4 TH: Switch, TH: Case Multi-condition judgment

<div th:switch="${age}">
    <span th:case="18"<span style = "max-width: 100%; clear: both; min-height: 1em;case="19"< p style = "max-width: 100%; clear: both; min-height: 1em;case="*"> Other </spa> </div>Copy the code

Note: The default option is specified using th:case=”*”.

Th: 1.5 each loop

HTML code:

<div th:each="name,item:${names}">
    <span th:text="${item.count}"></span>
    <span th:text="${name}"></span>
</div>
Copy the code

Java code:

@RequestMapping("/")
public ModelAndView index() {
    ArrayList<String> names = new ArrayList<>();
    names.add("java");
    names.add("golang");
    names.add("nodejs");
    ModelAndView modelAndView = new ModelAndView("/index"); 
    modelAndView.addObject("names",names);
    return modelAndView;
}
Copy the code

The access effect is as follows:

Where item is the detailed value of each line, and key is as follows:

  • Index index, starting at 0
  • Count is the x number, starting at 1
  • Size Specifies the size of the collection
  • Current Indicates the value of the current row

1.6 Th: Fragment, TH: INSERT, TH :replace, th:include code fragment reuse

  • Th: Fragment tag is a declaration of code fragments, used to solve the problem of code reuse, just like the common code written by Java programs, each needed place can be directly called;
  • Th :insert references fragment code, keeping its own main tag;
  • Th :replace references the fragment code without retaining its own main tag;
  • Th :include is similar to th:replace. Thymeleaf3.0 is not recommended.

Footer.html:

<! DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"<div th:fragment= </title> </head> <body> <div th:fragment="copyright"<div th:fragment= <div th:fragment="about"> </div> <div th:fragment="links">
    CCTV
</div>

</body>
</html>
Copy the code

Two code snippets are declared, copyright and About.

Cat.html page code:

<! DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"> <title> </head> <body> <div th:replace="footer :: copyright"></div>

<div th:insert="footer :: about"></div>

<div th:include="footer :: links"></div>
</body>
</html>
Copy the code

The first div refers to the copyright snippet of footer.html, and the second div refers to the About snippet of footer.html.

The “::” double colon is used to refer to page fragments, much like PHP syntax, which uses double colons to refer directly to static properties and methods of a class.

The execution effect is shown as follows:

Summary: The difference between th:insert, th:replace, and th:include is whether to keep their own main tags. Th :include is not recommended after 3.0, and can be replaced by th:replace tag.

Upgrade class – Fragment code pass reference

Using fragment, we can pass parameters in HTML code. For example, we define a top. HTML with a prompt of “welcome XXX”, and the name XXX needs to be passed dynamically, so that we can maximize the reuse of the code, which is a good use scenario. We need to do that.

Page main.html code:

<! DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org"
>
<head>
    <meta charset="UTF-8"> <title> </head> <body> <div th:replace="Footer :: webcome(' Lao Wang ')"></div>

</body>
</html>
Copy the code

Top page. HTML

<! DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org"
>
<head>
    <meta charset="UTF-8"<div th:fragment= </title> </head> <body> <div th:fragment="webcome(about)">
    <span th:text="' Welcome: '+${about}"></span>
</div>

</body>
</html>
Copy the code

The end result:

1.7 th:with defines local variables

Page code:


      
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org"
>
<head>
    <meta charset="UTF-8">
    <title>Wang Lei's blog</title>
</head>
<body>
<div th:with="sum=4-2">
    <span th:text="${sum}"></span>
</div>
</body>
</html>
Copy the code

The output is as follows: 2

1.8 th:remove Deletes a label

Th :remove is used to remove HTML code, th:remove values have five:

  • All Deletes all code in this section
  • Body Removes all elements within the main tag
  • Tag Removes the main tag and keeps all elements of the main tag
  • All-but-first keeps the main tag and the first element, and deletes everything else
  • None Does not delete any tags

The code for the sample index.html is as follows:

<! DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"</title> </head> <body> <div id="all" th:remove="all">
    <span>all</span>
    <span>1</span>
</div>

<div id="body" th:remove="body">
    <span>body</span>
    <span>2</span>
</div>

<div id="tag" th:remove="tag">
    <span>tag</span>
    <span>3</span>
</div>


<div id="all-but-first" th:remove="all-but-first">
    <span>all-but-first</span>
    <span>4</span>
</div>

<div id="none" th:remove="none">
    <span>none</span>
    <span>5</span>
</div>

</body>
</html>
Copy the code

The final display effect is as follows:

1.9 Other Labels

  • Th :style defines the style<div th:style="'color:'+${skinColor}">
  • Th :onclick Event<input type="button" value=" Click " th:onclick="'onsub()'">
  • Th :href The assignment attribute href<a th:href="${myhref}"></a>
  • Th :value Specifies the value attribute<input th:value="${user.name}" />
  • Th: SRC value assignment of SRC<img th:src="${img}" />
  • Th :action Assigns the property action<form th:action="@{/suburl}">
  • Th :id Indicates the ID of the assignment attribute<form id="${fromid}">
  • Th :attr defines multiple attributes<img th:attr="src=@{/img/stone.jpg},alt=${alt}" />
  • Th :object Defines an object<div th:object="${user}">
  • .

2. Expression usage

2.1 Expression Overview

2.1.1 Simple expressions

Variable expression: ${… } Select variable expressions: *{… } message expression: #{… } link expression: @{… } fragment expression: ~{… }

2.1.2 Data type

Text: ‘one text’, ‘Another one! ‘,… Numeric text: 0, 34, 3.0, 12.3… Boolean text: true, false NULL text: NULL Text marker: one, someText, main…

2.1.3 Text Operation

String concatenation: + literal replacement: | The name is ${name} |

2.1.4 Arithmetic operation

Binary operators: +, -, *, /, % Minus (unary operator) : –

2.1.5 Boolean operation

Binary operators: and, or Boolean negative (unary operator) :! , false

2.1.6 Conditional operators

Comparison values: >, <, >=, <= equal judgment: ==,! =

2.1.7 Condition judgment

If-then :(if)? (then) if-then – otherwise :(if)? (then) : (else) default: (value)? : (defaultvalue)

All of these expressions can be combined and nested, for example:

‘User is of type ‘ + ({user.type} ? : ‘Unknown’))

2.2 Expression Usage Examples

2.2.1 Variable Expression ${… }

The use of variable expressions, as we have seen in the previous code, is the most commonly used expression in our daily development. It is used to map the dynamic data of the background Java class to the page, for example:

Java code:

public ModelAndView index(a) {
    ModelAndView modelAndView = new ModelAndView("/cat");
    modelAndView.addObject("data"."I am Lao Wang.");
    return modelAndView;
}
Copy the code

HTML code:

<! DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"< p style = "max-width: 100%; clear: both; min-height: 1em"${data}"></span>
</body>
</html>
Copy the code

End result:

2.2.2 Selecting an expression *{… }

Selecting an expression is equivalent to selecting an object. Instead of using the prefix of the object, use the key of the attribute to display the content. The code is as follows:

<div th:object="${goods}">
    <span th:text="${goods.name}"></span>
    <span th:text="*{price}"></span>
    <span th:text="${#dates.format(goods.createTime, 'yyyy-MM-dd HH:mm:ss')}"></span>
</div>
Copy the code

End result:

7999.0 the 2018-08-10 14:03:51 the iMacCopy the code

*{goods. Price} = ${goods. Price}

2.2.3 Link Expression @{… }

To convert urls, the code is as follows:

<a th:href="@{/footer(id=666,name=laowang)}"> link < / a >Copy the code

The final result:

<a href="/footer? Id = 666 & name = laowang "> link < / a >

Link expressions that can pass arguments, separated by commas.

Server root relative path: @{~/path/to/something}

2.2.4 Text Operations

Text operations are divided into two parts: text add and text replace

Text spelling:

<span th:text="' my name is' + ${name}"></span>
Copy the code

Text replacement:

Textual substitution syntax: | content ${tag} |

<span th:text=| my name is "${name}, is a development engineer. |"></span>
Copy the code
2.2.5 Ternary expressions
2.2.6 Functions of double brackets
<p th:text="${val}">.</p>
<p th:text="${{val}}">.</p>
Copy the code

Results:

<p>1234567890</p>
<p>1234567890</p>
Copy the code
2.2.7 Embedding text Labels

While standard tags can be used for almost any business scenario, there are some situations where we prefer to write HTML text directly, such as:

<p>Hello, [[${name}]]</p>
Copy the code

Embedded text can be written as “[[…]]” and “[(…)].” Th :text and th:utext, for example:

<p>
    [[${name}]]
</p>
<p>
    [(${name})]
</p>
Copy the code

The result looks like this:

2.3 Overview of Expression objects

The objects in the expression can help us deal with the content to be displayed. For example, the dates utility class of the expression can format the time. Skilled use of these built-in classes can improve the efficiency of using Thymeleaf.

2.3.1 Expression base object
  • #ctx: Operates on the current context.
  • #vars:Manipulate context variables.
  • #request: (For Web projects only)HttpServletRequestObject.
  • #response: (For Web projects only)HttpServletResponseObject.
  • #session: (For Web projects only)HttpSessionObject.
  • #servletContext: (For Web projects only)ServletContextObject.
2.3.2 Expression utility classes
  • #execInfoThe utility class for manipulating templates, which contains template information such as:${#execInfo.templateName} .
  • #uris: URL processing tool
  • #conversions: methods for executing the configured conversion service (if any).
  • #dates: Method comes fromjava.util.DateObject for processing time, such as formatting.
  • #calendars: similar to#datesBut fromjava.util.CalendarObject.
  • #numbers: Used to format numbers.
  • #strings: methods for String objects: contains, startsWith, prepending/appending, etc.
  • #objects: a common object object method.
  • #bools: a tool for determining type bool.
  • #arrays: Array manipulation tool.
  • #lists: Lists operation data.
  • #sets: Set operation tool.
  • #mapsMap Operation tool.
  • #aggregates: a tool for manipulating arrays or collections.

Each class in the specific methods, click to view: www.thymeleaf.org/doc/tutoria…

3.IDEA Set Thymeleaf auto-completion

First, the effect picture:

IDEA is opens the Thymeleaf plugin support by default, if you don’t trust need to verify, please visit: www.jetbrains.com/help/idea/2.

The Thymeleaf namespace XMLNS :th=”http://www.thymeleaf.org” is declared in HTML. The complete code is as follows:


      
<html  xmlns="http://www.w3.org/1999/xhtml"
       xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h2 th:text="${hi}"></h2>
</body>
</html>
Copy the code

The key code is:

xmlns:th=”www.thymeleaf.org”

This way, when you type “th:” into the code, you’ll see all the tags for Thymeleaf.

Spring Boot integration Thymeleaf

3.1 Development Environment

  • Spring Boot 2.0.4
  • Thymeleaf 3.0.9
  • Jdk 8
  • Windows 10
  • The IDEA of 2018.2

Before formally integrating the Thymeleaf engine, take a look at the following directory structure:

3.2 Spring MVC directory structure

Apart from the package name, let’s explain what these directories represent:

  • Common Common public class
  • Controller Controller class
  • Dao data interaction classes
  • Service Business logic processing class
  • Application.java startup file
  • Resources Static file storage folder
  • Resources /templates All Thymeleaf directories hold directories
  • Resources/application. The properties global configuration classes
  • XML Maven configuration file

3.3 Spring Boot integration Thymeleaf consists of four steps:

  1. Pom.xml adds the Thymeleaf template engine
  2. Application. properties Configures Thymeleaf information
  3. Create the Controller class and write the code
  4. Create templates and write HTML code

Next, let’s look at the specific steps.

3.3.1 Pom.xml Adds the Thymeleaf template engine

<! --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>Copy the code

3.3.2 application.properties Configure Thymeleaf information

# Enable cache: It is recommended that production be enabled
spring.thymeleaf.cache=false
# Suggest whether a template exists
spring.thymeleaf.check-template-location=true
# Content - Type value
spring.thymeleaf.servlet.content-type=text/html
# Enable/disable
spring.thymeleaf.enabled=true
# template coding
spring.thymeleaf.encoding=utf-8
# Comma-separated list of view names that should be excluded from parsing
spring.thymeleaf.excluded-view-names=
# Template mode
spring.thymeleaf.mode=HTML5
# template storage path
spring.thymeleaf.prefix=classpath:/templates/
# template suffix
spring.thymeleaf.suffix=.html
Copy the code
Thymeleaf Common configuration description
Configuration items type The default value Recommended values instructions
spring.thymeleaf.enabled bool true The default Whether to enable
spring.thymeleaf.mode String HTML The default Template type, which can be set to HTML5
spring.thymeleaf.cache bool true The default Whether to enable cache. You are advised to set this parameter to true in the generation environment
spring.thymeleaf.prefix String classpath:/templates/ The default Path for storing templates
spring.thymeleaf.suffix String .html The default Template suffix
spring.thymeleaf.servlet.content-type String text/html The default The content-type value
spring.thymeleaf.encoding String utf-8 Template code

3.3.3 Create the Controller class and write the code

We create index.java in the Controller folder as follows:

package com.hello.springboot.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
@RequestMapping("/")
public class Index {

    @RequestMapping("/")
    public ModelAndView index(a) {
        ModelAndView modelAndView = new ModelAndView("/index");
        modelAndView.addObject("name"."Wang Lei's Blog");
        returnmodelAndView; }}Copy the code

Key code interpretation:

  1. ResponseBody annotation: If this annotation is used, the return result is printed directly instead of being rendered by the template engine
  2. Using the ModelAndView object, specify the view name & Add the view object

3.3.4 Create templates and write HTML codes

Create index.html under Resources /templates as follows:


      
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Wang Lei's blog</title>
</head>
<body>
<span th:text="${name}"></span>
</body>
</html>
Copy the code

To start debugging, type http://localhost:8080/ in your browser

The effect is as follows:

GitHub: github.com/vipstone/sp…

Iv. Reference materials

Official document thymeleaf thymeleaf: www.thymeleaf.org/doc/tutoria…

Thymeleaf official documentation Spring + thymeleaf: www.thymeleaf.org/doc/tutoria…