What is Thymeleaf?

Thymeleaf is a templating engine similar to Velocity and FreeMarker that can completely replace JSPS.

What are its advantages? Why do we use it?

1.Thymeleaf works both on and off the Internet, that is, it allows artists to view static pages in the browser and programmers to view dynamic pages with data in the server. This is because it supports HTML prototypes and then adds additional attributes to HTML tags to achieve the template + data presentation.

2. Can directly apply template to achieve JSTL, OGNL expression effect, avoid every day set template, the JSTL, change the label trouble. Developers can also extend and create custom dialects.

3. Can quickly achieve form binding, attribute editor, internationalization and other functions.

How can we make simple use of it quickly?

1. Simple Thymeleaf application

1) need to join the thymeleaf – 2.1.4. RELEASE. Jar (www.thymeleaf.org/download.ht)… Package, if using Maven, add the following configuration

<dependency>
    <groupId>org.thymeleaf</groupId>
    <artifactId>thymeleaf</artifactId>
    <version>2.1.4</version>
</dependency>
Copy the code

2) Then add the header file (as follows)

<! DOCTYPEhtml>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org">
Copy the code

3) Static data can be dynamically replaced with th tags. Messages from the background will replace the static data “Red Chair”, and if you visit a static page, the data “Red Chair” will display.

<td th:text="${message}">Red Chair</td>
Copy the code

Example demonstration:

Accessing static pages

 

4) Use cycles

Example demonstration:

controller:

@RequestMapping("index") public String replace(ModelMap map){ map.put("hello","hello thymeleaf !" ); List<String> list = new ArrayList<>(); List<String> list2 = new ArrayList<>(); for (int i = 0; i < 5; I ++) {list.add(" element "+ I); List2. Add (" members "+ I); } map.put("list",list); map.put("list2",list2); return "index"; }Copy the code

The index page:

<body>
    <! - values -- -- >
    <div th:text="${hello}">hello html !</div>

    <! - cycle -- -- >
    <div th:each="str:${list}">
        <div th:text="${str}"></div>
    </div>
    <div th:each="str:${list2}" th:text="${str}"></div>
</body>
Copy the code

Results:

hello thymeleaf ! Element 0 Element 1 element 2 element 3 Element 4 Member 0 Member 1 Member 2 Member 3 Member 4Copy the code

Note: It loops mainly depending on where you put the loop element

5) to determine

Example demonstration:

The index page:

<! Judging -- -- -- > < div th: if = "1 = = 1" > this element is < / div > < div th: text = "(1 = = 0)? 'This element exists ':' this element does not exist '"></div>Copy the code

Results:

The element exists. The element does not existCopy the code

6) Page introduction

Example demonstration:

The first way:

The index page:

<! <div th:include="a"></div>Copy the code

A page:

<! DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"> <head> <meta <div th:fragment="b"> </div> </body> </ HTML >Copy the code

Results:

Imported page A Fragment B of imported page ACopy the code

The second way:

<! <div th:include="a::b"></div>Copy the code

A page the same, result:

Section B of page A is introducedCopy the code

7) Function call

Example demonstration:

The index page:

<! DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <! - cycle -- -- > < div th: each = "STR: ${list}" > < div th: text = "${STR}" > < / div > < / div > < div th: each = "STR: ${list2}" th:text="${str}"></div> <! Judging -- -- -- > < div th: if = "1 = = 1" > this element is < / div > < div th: text = "(1 = = 0)? 'This element exists ':' this element does not exist '"></div> <! <div th:include="a::b"></div> <! <div th:text="${hello}">hello HTML! </div> <! -- js function call --> <! - function call - > < a th: href = "' javascript: a (\ '${hello} + +' \ '); </a> <script language="JavaScript"> function a(hello) {alert(hello); } </script> </body> </html>Copy the code

controller:

@RequestMapping("index") public String replace(ModelMap map){ map.put("hello","hello thymeleaf !" ); List<String> list = new ArrayList<>(); List<String> list2 = new ArrayList<>(); for (int i = 0; i < 5; I ++) {list.add(" element "+ I); List2. Add (" members "+ I); } map.put("list",list); map.put("list2",list2); return "index"; }Copy the code

Results:

8) Other circumstances

Example demonstration:

Case 1: the case where userInfos has a value

controller:

List<UserInfo> userInfos = new ArrayList<>(); for (int i = 0; i < 5; i++) { UserInfo userInfo = new UserInfo(); The userInfo. Elegantly-named setName (" small "+ I); userInfos.add(userInfo); } map.put("userInfos",userInfos);Copy the code

The index page:

<! Other information -- -- -- > < div th: each = "user: ${userInfos}" th: text = "${user. The name}" > < / div >Copy the code

Results:

Small 0 small 1 small 2 small 3 small 4Copy the code

Second case: userInfos has no value

Controller:

List<UserInfo> userInfos = new ArrayList<>(); for (int i = 0; i < 5; i++) { UserInfo userInfo = new UserInfo(); The userInfo. Elegantly-named setName (" small "+ I); userInfos.add(userInfo); } map.put("userInfos",null);Copy the code

Page unchanged, result none, no output

The third case:

Controller:

UserInfo userInfo = new UserInfo(); The userInfo. Elegantly-named setName (" wang "); map.put("userInfo",null);Copy the code

The index page:

<div th:text="${userInfo.name}" ></div>
Copy the code

A null-pointer exception is reported in this case.

How to solve this problem?

The index page:

<div th:text="${userInfo? .name}" ></div> <! If thymeleaf uses a number formatting function, the number must not be empty. Otherwise, a type conversion error will be reported.Copy the code

If it is not empty, it will be adjusted. If it is empty, no error will be reported.

 

Freemarker gets started with a small DEMO

Engineering introduction dependency

<dependency><groupId>org.freemarker</groupId><artifactId>freemarker< / artifactId > < version > 2.3.23 < / version > < / dependency >

 

 

Creating a template File

Four elements in a template file

<#–… 3, Interpolation: ${.. 4, FTL directive: FreeMarker directive, similar to HTML markup, with # before the name to separate, will not output.

Let’s now create a simple create template file called test.ftl

<html><head><meta charset=”utf-8″><title>Freemarker</title></head><body><#– I’m just a comment, I won’t have any output –>${name}, hello. ${message}</body></html>

There is text, interpolation and comments

Generate the file

Use steps:

Step 1: Create a Configuration object and simply new it. The constructor takes the version number of Freemarker.

Step 2: Set the path for the template file.

Step 3: Set the character set used by the template file. It’s usually UTF-8.

Step 4: Load a template and create a template object.

Step 5: Create a data set to be used by the template, either a POJO or a Map. Usually a Map.

Step 6: Create a Writer object, usually a FileWriter object, and specify the name of the file to be generated.

Step 7: Call the process method output file of the template object.

Step 8: Close the stream

Code:

Create Test class main as follows:

//1. Create a Configuration classnew Configuration(Configuration.getVersion()); / / (2) set in the template directory configuration. SetDirectoryForTemplateLoading (newFile(“D:/work/freemarkerDemo/src/main/resources/”)); / / 3. Set the character set configuration. SetDefaultEncoding (” utf-8 “); / / 4. Load the Template Template Template = configuration. GetTemplate (” test. FTL “); //5. Create data modelMap map=new HashMap(a);map *.put(支那“name”支那.支那“Zhang”支那) *;map *.put(支那“message”支那.支那“Welcome to the magical world!”支那)*; //6. Create a Writer object. Writer out =new FileWriter(newFile(“d:\\test.html”)); Template. process(map, out); //8. Close the Writer object out.close();

 

The test.html file is displayed in the root directory of drive D