Spring Boot Best Practices (iv) template engine Thymeleaf integration

Source: Internet
Author: User
Tags create index utext
I. Introduction of 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 an MVC-based Web application, but it can handle any XML file even in an offline environment. It provides a complete spring framework integration.

On spring recommended Thymeleaf This statement, I did not see in the spring Official document specific instructions, but in comparison with the JSP, said JSP and Thymeleaf compared to some of the shortcomings of JSP, And Thymeleaf just as a representation of other template engines.

As an excellent template engine, in addition to ease of use, active community, healthy and rapid development, there is a very important point is the performance, that Thymeleaf 3 and freemaker performance comparison is how, follow-up articles will be updated in succession.

Second, Thymeleaf basic use

The use of thymeleaf is made up of two parts: the tag + expression, the tag is the grammatical structure of the thymeleaf, and the expression is the content implementation in the syntax.

With the tag + expression, the data and template are combined and eventually converted into HTML code, which is returned to the user.

Thymeleaf Basic use is divided into three parts:

    1. Label use
    2. Expressions use
    3. Set idea to Thymeleaf code completion
1. Label using 1.1st:text basic information output

HTML code:

<!DOCTYPE html>

Java code:

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

Final effect:老王

1.2 Th:utext HTML content output

Using "Th:text" is the same as the output of the content, using "Th:utext" can be HTML label output.

Java code:

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

HTML code:

Display effect:

1.3rd:if, th:unless condition judgment
<span th:if="${age > 18}">    成年</span><span th:unless="${age > 18}">    未成年</span>

Th:if to meet the conditions of business processing, th:unless just the opposite, is to remove the meaning.

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 uses the th:case="*" specified.

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 for each row, the key value is as follows:

    • Index subscript, starting from 0
    • Count x, starting from 1
    • Size of this collection
    • Current row value
1.6th:fragment, Th:insert, Th:replace, Th:include code snippet multiplexing
    • The th:fragment tag is a declarative code fragment that solves the problem of code reuse, like the common code written by the Java program, which can be called directly in every desired place;
    • Th:insert references fragment's code, retains its own main tag;
    • Th:replace references Fragment's code, does not retain its own main tag;
    • Th:include is not recommended for use with similar th:replace,thymeleaf3.0;

Footer.html page Code:

<!DOCTYPE html>

Two code snippets were declared, copyright and about.

Cat.html page Code:

<!DOCTYPE html>

The first div refers to the footer.html's copyright code fragment, and the second div references the footer.html's about code snippet.

Double Colon Understanding: It uses the "::" Double colon to complete a reference to the page fragment, a bit like the syntax inside PHP, using a double colon to represent the static properties and methods of the class directly reference.

Execution effects such as:

Summary: you can clearly see the difference between Th:insert, Th:replace, th:include, whether to retain their own main label, Th:include after 3.0 has not been recommended, you can use th: Replace label overrides.

Accelerated--fragment Code Transfer parameter

Using fragment we can be in the HTML code, such as we define a top.html there is a "welcome xxx" hint, and this name XXX is required to dynamically transfer, so that we can maximize the completion of code reuse, This time is a good use of the scene, we need to do so.

Page main.html Code:

<!DOCTYPE html>

Page top.html

<!DOCTYPE html>

The final effect:

1.7 Th:with defining Local variables

Page code:

<!DOCTYPE html>

Page Output results: 2

1.8 Th:remove Deleting tags

Th:remove is used for the deletion of HTML code with a value of five th:remove:

    • All delete all code in this paragraph
    • Body Delete all elements within the main tag
    • Tag deletes the main tab, preserving all elements of the main tag
    • All-but-first retains the primary label and the first element, all other deletions
    • None does not remove any labels

The example index.html code is as follows:

<!DOCTYPE html>

The results of the final display are as follows:

1.9 Other Tags
    • Th:style Defining styles<div th:style="'color:'+${skinColor}">
    • Th:onclick Click events<input type="button" value=" Click " th:onclick="'onsub()'">
    • Th:href Assignment Property href<a th:href="${myhref}"></a>
    • Th:value Assignment Property value<input th:value="${user.name}" />
    • TH:SRC Assignment src
    • Th:action Assignment Property Action<form th:action="@{/suburl}">
    • Th:id Assignment Property ID<form id="${fromid}">
    • Th:attr Defining multiple properties
    • Th:object defining an Object<div th:object="${user}">
    • ...
2. Expression using 2.1 expression Summary 2.1.1 Simple expression

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

Types of 2.1.2 Data

Text: ' One text ', ' another one! ',...
Digital text: 0, 3.0, 12.3,...
Boolean literal: True, False
NULL literal: null
Text markers: One, sometext, main,...

2.1.3 Text Manipulation

string concatenation: +
Literal substitution: | The name is ${name}|

2.1.4 Arithmetic operations

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

2.1.5 Boolean operations

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

2.1.6 Conditional operators

Comparison value: <, >=, <=
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.isadmin ()}? ' Administrator ': (${user.type}?: ' Unknown '))

2.2 Expressions use an instance 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 usual development, to map the dynamic data of the background Java class to the page, for example:

Java code:

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

HTML code:

<!DOCTYPE html>

Final effect:

2.2.2 Select expression *{...}

The selection expression is equivalent to selecting an object that is not prefixed to the object when it is used, and uses the attribute's key to display the content directly, with the following code:

<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} simply eliminates the "goods." Prefix, the effect is the same.

2.2.3 link expression @{...}

To convert the URL, the code is as follows:

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

The result of the final rendering:

<a href="/footer?id=666&name=laowang">链接</a>

Link expressions, which can be passed as arguments, separated by commas.

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

2.2.4 Text Manipulation

Text operations are divided into two: text spelling, text substitution

Text spelling:

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

Text substitution:

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

<span th:text="|我叫${name},是一名开发工程师。|"></span>
2.2.53-Dollar Expression
2.2.6 Double Bracket Action
<p th:text="${val}">...</p><p th:text="${{val}}">...</p>

Results:

<p>1234567890</p><p>1,234,567,890</p>
2.2.7 Embedding Text Labels

While standard tags can meet almost all business scenarios, in some cases we prefer to write directly to HTML text, for example:

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

Embedded text has two ways of writing "[[...]]" and "[(...)]", respectively, like Th:text and Th:utext, for example:

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

See the effect is this:

2.3 Overview of Expression objects

The object in the expression can help us to deal with the content that we want to show, such as the tool class of the expression dates can format time, these built-in classes use skillfully, can let us use thymeleaf efficiency to improve a lot.

2.3.1 Expression Base Object
    • #ctx: Manipulate the current context.
    • #vars:The action context variable.
    • #request: (for Web project only) HttpServletRequest objects.
    • #response: (for Web project only) HttpServletResponse objects.
    • #session: (for Web project only) HttpSession objects.
    • #servletContext: (for Web project only) ServletContext objects.
2.3.2 Expression Utility Class
    • #execInfo : The tool class that operates the template, including some template information, such as: ${#execInfo. templatename} .
    • #uris : tool for URL processing
    • #conversions : Methods for executing the configured conversion service (if any).
    • #dates : Method from java.util.Date object for processing time, such as: Formatting.
    • #calendars : Similar to #dates , but from the Java.util.Calendar object.
    • #numbers : Used to format numbers.
    • #strings : Methods for String objects:contains, StartsWith, prepending/appending, etc.
    • #objects : Normal object method.
    • #bools : A tool that determines the type of bool.
    • #arrays : Array manipulation tool.
    • #lists : List operation data.
    • #sets : Set manipulation tool.
    • #maps : Map Operation tool.
    • #aggregates : A tool that operates an array or collection.

Specific methods in each class, click to view: www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#appendix-b-expression-utility-objects

3.IDEA Set Thymeleaf Auto complete

First on:

Idea is enabled by default Thymeleaf plug-in support, if you do not trust the need to verify, please visit: www.jetbrains.com/help/idea/2018.2/thymeleaf.html

But just configuring the above effect is still not working, because you want to declare the Thymeleaf namespace in HTML xmlns:th="http://www.thymeleaf.org" , the complete code is as follows:

<!DOCTYPE html>

The key code is:

Xmlns:th= "Http://www.thymeleaf.org"

So when you enter "th:" In the code, you will see all the tags of Thymeleaf.

Third, Spring Boot integrated Thymeleaf3.1 development environment
    • Spring Boot 2.0.4
    • Thymeleaf 3.0.9
    • JDK 8
    • Windows 10
    • Idea 2018.2

Before formally integrating the Thymeleaf engine, consider the directory structure

3.2 Spring MVC directory structure

To remove the package name, let's explain what these directories mean:

    • Common general public class
    • Controller Controllers Class
    • DAO Data Interaction Classes
    • Service business logic Processing class
    • Application.java Startup file
    • Resources Static File storage folder
    • Resources/templates all thymeleaf Directory storage directory
    • Resources/application.properties Global Configuration Class
    • Pom.xml Maven configuration file
3.3 Spring Boot Integrated Thymeleaf is divided into four steps:
    1. Pom.xml adding Thymeleaf template engine
    2. Application.properties Configuring Thymeleaf Information
    3. Create a controller class, write code
    4. Create templates, write HTML code

Next, we look at specific steps separately.

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 Configuration 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 Instructions
Configuration Items type Default Value Recommended Values Description
Spring.thymeleaf.enabled bool True Default is enabled
Spring.thymeleaf.mode String Html Default Template type, which can be set to HTML5
Spring.thymeleaf.cache bool True Default If caching is enabled, the build environment recommendation is set to True
Spring.thymeleaf.prefix String classpath:/templates/ Default Template Storage Path
Spring.thymeleaf.suffix String . html Default Template suffix
Spring.thymeleaf.servlet.content-type String Text/html Default Content-type value
Spring.thymeleaf.encoding String - Utf-8 Template encoding
3.3.3 Creating a controller class, writing code

We create Index.java in the Controller folder with the following code:

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:

    1. @ResponseBody Note: If you use this annotation, the returned results will be output directly instead of being rendered using the template engine
    2. Use the Modelandview object to specify the view name & Add View Object
3.3.4 creating templates, writing HTML code

We create the index.html under Resources/templates, the code is as follows:

<!DOCTYPE html>

Start debugging, in Browser input: http://localhost:8080/

The effect is as follows:

Related Code github:github.com/vipstone/springboot-example.git

Iv. references

Thymeleaf Official Document Thymeleaf:www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html

Thymeleaf Official documents Spring + THYMELEAF:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.