Spring boot (IV) template engine thymeleaf integration

1、 Introduction to thymeleaf

Thymeleaf is a Java XML / XHTML / HTML5 template engine that can be used in web and non web environments. It is more suitable for providing 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 complete spring framework integration.

As for spring's recommendation of thymeleaf, I didn't see a specific description in the official spring document, but when comparing with JSP, I said some shortcomings of JSP and thymeleaf compared with JSP, and thymeleaf is only a representative of other template engines.

As an excellent template engine, in addition to ease of use, active community and healthy and rapid development, a very important point is performance. What is the performance comparison between thymeleaf 3 and freemaker? Subsequent articles will be updated one after another.

2、 Thymeleaf foundation use

The usage of thymeleaf consists of two parts: tag + expression. Tag is the syntax structure of thymeleaf, and expression is the implementation of the content in the syntax.

Through tag + expression, combine the data with the template, and finally convert it into HTML code and return it to the user.

The use of thymeleaf foundation is divided into three parts:

1. Label use

1.1 th: textbasic information output

HTML code:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org">
<head>
    <Meta charset="UTF-8">
    <title>王磊的博客</title>
</head>
<body>
<span th:text="${name}"></span>
</body>
</html>

Java code:

@RequestMapping("/")
public ModelAndView index() {
    ModelAndView modelAndView = new ModelAndView("/index");
    modelAndView.addObject("name","老王");
    return modelAndView;
}

Final effect: Lao Wang

1.2 th: utext HTML content output

Use "th: text" to output the content as is, and use "th: utext" to output HTML tags.

Java code:

@RequestMapping("/eat")
public ModelAndView eat() {
    ModelAndView modelAndView = new ModelAndView("/cat");
    modelAndView.addObject("data","<span style='color:red'>老王是吃货</span>");
    return modelAndView;
}

HTML code:

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

Display effect:

1.3 th: if, th: unless condition judgment

<span th:if="${age > 18}">
    成年
</span>
<span th:unless="${age > 18}">
    未成年
</span>

Th: if is the business processing that meets the conditions. Th: unless is just the opposite. It means to remove.

1.4 th: switch, th: case multi condition judgment

<div th:switch="${age}">
    <span th:case="18">18岁</span>
    <span th:case="19">19岁</span>
    <spa th:case="*">其他</spa>
</div>

Note: the default option is specified with th: case = "*".

1.5 th: each cycle

HTML code:

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

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;
}

The access effect is as follows:

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

1.6 reuse of th: fragment, th: insert, th: replace and th: include code fragments

footer. 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>王磊的博客</title>
</head>
<body>

<div th:fragment="copyright">
    © 著作权归 老王 所有
</div>

<div th:fragment="about">
    关于
</div>

<div th:fragment="links">
    CCTV
</div>

</body>
</html>

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>王磊的博客</title>
</head>
<body>
<div th:replace="footer :: copyright"></div>

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

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

The first div refers to footer The copy code snippet of HTML, and the second div refers to footer About code snippet of HTML.

Understanding of double colons: the "::" double colons are used to complete the reference to page fragments, which is a bit like the syntax in PHP. The double colons are used to represent the direct reference to the static properties and methods of the class.

The execution effect is as follows:

Summary: it can be clearly seen that the difference between th: insert, th: replace and th: include lies in whether to keep their own primary tag. Th: include is not recommended after 3.0, and can be replaced by th: replace tag.

Improvement class - fragment code transfer parameter

Using fragment, we can pass parameters in HTML code. For example, we define a top HTML contains a prompt of "welcome XXX", and the name XXX needs to be dynamically passed, so that we can reuse the code to the greatest extent. This is a good use scenario, and we need to do so.

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>王磊的博客</title>
</head>
<body>

<div th:replace="footer :: webcome('老王')"></div>

</body>
</html>

Page top html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org"
>
<head>
    <Meta charset="UTF-8">
    <title>王磊的博客</title>
</head>
<body>

<div th:fragment="webcome(about)">
    <span th:text="'欢迎:'+${about}"></span>
</div>

</body>
</html>

Final effect:

1.7 th: with defining local variables

Page code:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org"
>
<head>
    <Meta charset="UTF-8">
    <title>王磊的博客</title>
</head>
<body>
<div th:with="sum=4-2">
    <span th:text="${sum}"></span>
</div>
</body>
</html>

Page output result: 2

1.8 th: remove delete tag

Th: remove is used to delete HTML code. There are five th: remove values:

Example index The HTML code 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>王磊的博客</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>

The final display effect is as follows:

1.9 other labels

2. Expression usage

2.1 expression summary

2.1. 1 simple expression

Variable expression: ${...} Select variable expression: * {...} Message expression: #{...} Link expression: @ {...} Fragment Expression: ~ {...}

2.1. 2 type of data

Text: 'one text', 'another one!' Numeric text: 0,34,3.0,12.3,... Boolean text: true, false null text: null text tag: one, sometext, main

2.1. 3 text operation

String splicing: + literal replacement: | the name is ${name}|

2.1. 4 arithmetic operation

Binary operators: +, -, *, /,% minus sign (unary operator):-

2.1. 5 Boolean operation

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

2.1. 6 conditional operators

Comparison value: >, <, > =, < = equality judgment: = ==

2.1. 7 condition judgment

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

All the above expressions can be combined and nested, for example:

2.2 expression usage examples

2.2. 1 variable expression ${...}

We have seen the use of variable expressions in the previous code, $is the most commonly used expression in our normal development, which is used to map the dynamic data of background Java classes to the page, for example:

Java code:

public ModelAndView index() {
    ModelAndView modelAndView = new ModelAndView("/cat");
    modelAndView.addObject("data","我是老王");
    return modelAndView;
}

HTML code:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org">
<head>
    <Meta charset="UTF-8">
    <title>王磊的博客</title>
</head>
<body>
<span th:text="${data}"></span>
</body>
</html>

Final effect:

2.2. 2 select expression * {...}

The selection expression is equivalent to selecting an object. The prefix of the object is no longer required when using it. The content is displayed directly using the key of the attribute. 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>

Final effect:

iMac 7999.0 2018-08-10 14:03:51

Summary: * {price} = ${goods. Price} just omits "goods." Prefix, the effect is the same.

2.2. 3 link expression @ {...}

It is used to convert URLs. The code is as follows:

<a th:href="@{/footer(id=666,name=laowang)}">链接</a>

Final effect:

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

Link expressions, which can pass parameters, separated by commas.

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

2.2. 4 text operation

There are two text operations: text splicing and text replacement

Text collage:

<span th:text="'我叫'+${name}"></span>

Text substitution:

Syntax of text substitution: | content ${tag}|

<span th:text="|我叫${name},是一名开发工程师。|"></span>
2.2. 5 ternary expression
2.2. 6 double bracket action
<p th:text="${val}">...</p>
<p th:text="${{val}}">...</p>

result:

<p>1234567890</p>
<p>1,234,567,890</p>
2.2. 7 embedded text labels

Although standard tags can meet almost all business scenarios, we prefer to write HTML text directly in some cases, such as:

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

Embedded text can be written in two ways "[[...]]" And "[(...)]", Their functions are the same as th: text and th: utext, for example:

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

The effect is as follows:

2.3 expression object overview

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

2.3. 1 expression base object
2.3. 2 expression utility class

Click to view the specific methods in each class: https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#appendix -b-expression-utility-objects

3. Idea setting thymeleaf auto completion

Effect drawing first:

Idea is supported by thymeleaf plug-in by default. If you don't trust to verify, please visit: https://www.jetbrains.com/help/idea/2018.2/thymeleaf.html

However, just configuring the above effect still cannot be used normally. The reason is that you have to declare the thymeleaf namespace xmlns: th in HTML=“ http://www.thymeleaf.org ", the complete code 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>Title</title>
</head>
<body>
    <h2 th:text="${hi}"></h2>
</body>
</html>

The key codes are:

In this way, when you enter "th:" in the code, you will see all the tags of thymeleaf.

3、 Spring boot integrates thymeleaf

3.1 development environment

Before formally integrating thymeleaf engine, let's take a look at the following directory structure, as shown in the figure:

3.2 spring MVC directory structure

In addition to the package name, let's explain what these directories represent:

3.3 spring boot integrates thymeleaf in four steps:

Next, let's look at the specific steps.

3.3. 1 pom. XML add thymeleaf template engine

<!--thymeleaf模板-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

3.3. 2 application. Properties configure thymeleaf information

# 启用缓存:建议生产开启
spring.thymeleaf.cache=false
# 建议模版是否存在
spring.thymeleaf.check-template-location=true
# Content-Type 值
spring.thymeleaf.servlet.content-type=text/html
# 是否启用
spring.thymeleaf.enabled=true
# 模版编码
spring.thymeleaf.encoding=utf-8
# 应该从解析中排除的视图名称列表(用逗号分隔)
spring.thymeleaf.excluded-view-names=
# 模版模式
spring.thymeleaf.mode=HTML5
# 模版存放路径
spring.thymeleaf.prefix=classpath:/templates/
# 模版后缀
spring.thymeleaf.suffix=.html
Thymeleaf common configuration description

3.3. 3 create the controller class and write the code

We create index. In the controller folder Java, the code is 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() {
        ModelAndView modelAndView = new ModelAndView("/index");
        modelAndView.addObject("name","王磊的博客");
        return modelAndView;
    }
}

Key code interpretation:

3.3. 4 create a template and write HTML code

We create the index.xml under Resources / templates HTML, the code 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>王磊的博客</title>
</head>
<body>
<span th:text="${name}"></span>
</body>
</html>

Start debugging and enter in the browser: http://localhost:8080/

The effects are as follows:

Relevant code GitHub: https://github.com/vipstone/springboot-example.git

4、 References

Thymeleaf official document thymeleaf: https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html

Thymeleaf official document Spring + thymeleaf: https://www.thymeleaf.org/doc/tutorials/3.0/thymeleafspring.html

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>