1. The introduction

Explain template engine, we must not be unfamiliar, the first thing that comes to mind is JSP. Speaking of which, the JSP template engine has accompanied me almost the whole way from the Java Web to the familiar, the various tags can be said to be a collection. Spring Boot does not support the JSP template engine, so I have to support it, which is very sad. As a last resort, Spring Boot was used

One of the recommended template engines is Thymeleaf. Don’t know, it really feels very nice! Without further ado, let’s introduce.

2. Thymeleaf is introduced

To see Thymeleaf, you must visit www.thymeleaf.org/

The latest stable release is Thymeleaf 3.0.11

The official website introduces all kinds of NB and Nice, and summarizes the following points:

  • Thymeleaf is a server-side Java template engine for developing Web and standalone environment projects
  • Hymeleaf integrates perfectly with SpringMVC’s view technology and SpringBoot’s automated configuration at almost no cost, and you just have to focus on Thymeleaf’s syntax.

What I thought was the biggest characteristic in the beginning:

  • Thymeleaf is an HTML model, and its biggest advantage over JSP is that it doesn’t break the original HTML page, which means we can write our functionality without breaking the art design.

The characteristics of ID on the network are summarized:

  • Static and dynamic: Thymeleaf works in both online and offline environments, meaning it allows artists to view static pages in the browser and programmers to view dynamic pages with data on the server. This is because it supports HTML prototypes and then adds additional attributes to HTML tags to achieve the template + data presentation. Browsers ignore undefined tag attributes when interpreting HTML, so Thymeleaf’s template can run statically; When data is returned to the page, the Thymeleaf tag dynamically replaces the static content and makes the page display dynamically.
  • Out of the box: it provides standard and Spring standard two dialects, you can directly use the 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.
  • Multi-dialect support: Thymeleaf provides the Spring standard dialect and an optional module that integrates perfectly with SpringMVC to quickly implement form binding, property editor, internationalization, and more.
  • Perfect integration with SpringBoot, which provides the default configuration for Thymeleaf and sets up a view resolver for Thymeleaf, we can manipulate Thymeleaf just like we used to with JSPS. There is almost no difference in the code except in the template syntax.

3. Spring Boot introduces Thymeleaf

Start by creating a Spring Boot project (using Spring Boot 2.2.1) and adding dependencies

pom.xml

<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId>  </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies>Copy the code

Spring Boot auto-configuration already has Thymeleaf auto-configuration, which only takes effect when you introduce dependencies!

We can see that some Thymeleaf autoconfiguration has already defined the prefix (position) and suffix for reading template files

@ConfigurationProperties(
    prefix = "spring.thymeleaf"
)
public class ThymeleafProperties {
    private static final Charset DEFAULT_ENCODING;
    public static final String DEFAULT_PREFIX = "classpath:/templates/";
    public static final String DEFAULT_SUFFIX = ".html";
    private boolean checkTemplate = true;
    private boolean checkTemplateLocation = true;
    private String prefix = "classpath:/templates/";
    private String suffix = ".html";
    private String mode = "HTML";
Copy the code

4. Test examples

Write a Controller by hand: Demonstrate retrieving the contents of the Request, Session, and ServletContext fields

@Controller
public class DemoContoller {
    @Autowired
    private HttpSession session;
    @Autowired
    private ServletContext application;
    @GetMapping("/test01")
    public String m1(Model model){
        model.addAttribute("userName".Romance of The Three Kingdoms);
        session.setAttribute("author"."Luo Guanzhong");
        application.setAttribute("createDate".new Date());
        return "demo01"; }}Copy the code

Add the returned template to the default location:

The benefits of Thymeleaf’s static and static combination can be demonstrated here:

For example, my demo01 definition looks like this:

<! < HTML lang="en" XMLNS :th="http://www.thymeleaf.org"> <head> <meta charset=" utF-8 "> <title> title </title> </head> <body> <h1 th:text="${userName}"> </html>Copy the code

If it is a static file, it will show journey to the West:

<! DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <! - < h1 th: text = "${userName}" > monkey < / h1 > -- > < h2 > request access < / h2 > < h1 th: text = "${userName} + ', '+ ${userName}" > < / h1 > < h1 Th: text = "| ${# request. GetAttribute (" userName")}, ${# request. GetAttribute (" userName ")} | "> < / h1 > < h2 > session access < / h2 > < span  th:text="|${session.author},${session['author']},${#httpSession.getAttribute('author')}|"></span> </h2> <span th:text="${application.createDate}"></span> <span th:text="${#servletContext.getAttribute('createDate')}"></span> <span th:text="${application['createDate']}"></span> </body> </html>Copy the code

5.Thymeleaf

${} is not an EL expression, but an OGNL expression. ${} is an ogNL expression. Common usage:

  1. Format the date taken from the ServletContext above
<input type="text" th:value="${#dates.format(application.createDate)}">
Copy the code
  1. Action object

Entity:

public class User {
    private  Integer userId;
    private  String userName;
    private  Integer userAge;
    private  Integer userSex;
    private  String[] hobbyArray;
    public Integer getUserId(a) {
        return userId;
    }
    public void setUserId(Integer userId) {
        this.userId = userId;
    }
    public String getUserName(a) {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    public Integer getUserAge(a) {
        return userAge;
    }
    public void setUserAge(Integer userAge) {
        this.userAge = userAge;
    }
    public Integer getUserSex(a) {
        return userSex;
    }

    public void setUserSex(Integer userSex) {
        this.userSex = userSex;
    }
    public String[] getHobbyArray() {
        return hobbyArray;
    }
    public void setHobbyArray(String[] hobbyArray) {
        this.hobbyArray = hobbyArray; }}Copy the code

Controller:

@GetMapping("/test02")
    public String m2(Model model){
        User user=new User();
        user.setUserId(999);
        user.setUserName("The wu is empty");
        user.setUserAge(50);
        user.setUserSex(1);
        user.setHobbyArray(new String[]{"Basketball"."Football"."Music"});
        model.addAttribute("user",user);
        return "demo02";
    }
Copy the code

Thymeleaf template page:

< h1 > show data < / h1 > < ul > < li th: text = "${user. The userName}" > < / li > / / radio buttons on the choice of < li th: if = "${user. UserSex = = 1}" > boy < / li > < li Th: unless = "${user. UserSex = = 1}" > women < / li > < / ul > < ol th: object = "${user}" > < li th: text = "* {userName}" > < / li > < li Th: if = "* {userSex = = 1}" > boy < / li > < li th: unless = "* {userSex = = 1}" > women < / li > < / ol > < select name = "" id =" "> / / traversal < option value =" " th:each="hobby,vs:${user.hobbyArray}" th:value="|${vs.index},${vs.count}|" th:text="${hobby}"></option> </select> < h1 > [[${user. The userName}]] < / h1 > < script > var / / javascript data name = '[[${user. The userName}]], [[${user. UserSex}]]' alert (name); </script>Copy the code
  1. Other USES

Other usage of the time to consult, generally directly see the official website documents can!