SpringBoot integration [Thymeleaf template engine]

Table of contents 

1. What is Thymeleaf?

2. Why use Thymeleaf?

3. Using Thymeleaf

3.1 jar package dependencies 

3.2 Configure thymleaf in application.properties

4. Thymeleaf grammar and case operation

4.1 Source code analysis  

4.2 Case

4.2.1 th attribute 

   4.2.2 Practical operation


foreword 

   Spring Boot  [template engine] thymeleaf 

  • What is Thymeleaf?
  • Why use Thymeleaf?
  • Using Thymeleaf steps
  • Thymeleaf syntax in detail
    • Source code analysis
    • th attribute

1.  What is Thymeleaf  ?

Simply put, Thymeleaf is a template engine similar to Velocity and FreeMarker, which can completely replace JSP.
From the code level: Thymeleaf is a java class library, which is an xml/xhtml/html5 template engine, which can be used as the view layer of the MVC web application.

2. Why use Thymeleaf?

Disadvantages of using jsp 

  1. The project directory structure is cumbersome
  2. The page is not concise
  3. The jsp built-in error page cannot override the default error page of springboot
  4. Can only be marked as war but not jar
  5. The built-in jetty server does not support jsp

Advantages of Thymeleaf

  1. Out of the box, it provides standard and spring standard dialects. You can directly apply templates to achieve JSTL and OGNL expression effects, avoiding the troubles of setting templates, changing jstl, and changing labels every day. At the same time, developers can also extend and create custom dialects;
  2. Thymeleaf provides spring standard dialect and an optional module that is perfectly integrated with SpringMVC, which can quickly implement functions such as form binding, property editor, and internationalization.
  3. The template page can be executed with or without the network, and the page of the artist can be used. Compared with jsp, additional tags are reduced, and the page is more concise.

Note: Spring-boot supports FreeMarker, Thymeleaf, jsp, velocity. But the support for freemarker and thymeleaf is the best, jsp is not recommended 

3. Using Thymeleaf

  3.1 jar package dependencies 

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

   3.2 Configure thymleaf in application.properties

#  thymeleaf:
#    #前缀
#    prefix: classpath:/templates/
#    #后缀
#    suffix: .html
#    # 模板格式
#    mode: HTML5
#    encoding: UTF-8
#    servlet:
#      content-type: text/html
#    cache: false
#    check-template-location: true
  1. prefix: specify the directory where the template is located
  2. check-tempate-location: Check if the template path exists
  3. cache: Whether to cache, set it to false in development mode, to avoid restarting the server after changing the template, set it to true online, which can improve performance.
  4. encoding&content-type: Everyone should be familiar with this, and it has the same effect as setting the output corresponding attribute in Servlet.
  5. mode: For this, please refer to the description on the official website, and this is different from 2.X to 3.0.
spring.thymeleaf.mode = LEGACYHTML5

This configuration is not necessary, but the default value of spring.thymeleaf.mode is HTML5, which is actually a very strict check. Changing to LEGACYHTML5 can get a more friendly and friendly format requirement.

4. Thymeleaf grammar and case operation

4.1 Source code analysis  

     View part of the source code as follows

@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";
	...
}

Looking at the above source code, thymeleaf automatically configures the rule prefix and suffix, so as long as we put the html page under casspath:/templates/ , thymeleaf can automatically render.

4.2 Case

4.2.1 th attribute 

Thymeleaf basically has the attributes that html has, and there are about seven or eight commonly used attributes. Among them, the execution priority of the th attribute is from 1 to 8, and the lower the number, the higher the priority. 

  1. th:text : Set the text content of the current element. The same function is th:utext. The difference between the two is that the former will not escape html tags, but the latter will. Low priority: order=7
  2. th:value : Set the value of the current element, similar to modifying the specified attributes are th:src, th:href. Low priority: order=6
  3. th:each : Traversing the loop elements, used together with th:text or th:value. Pay attention to the label position modified by this attribute, see later for details. High priority: order=2
  4. th:if : Conditional judgment, similar to th:unless, th:switch, th:case. Higher priority: order=3
  5. th:insert : code block introduction, similar to th:replace, th:include, the difference between the three is quite large, if used improperly, it will destroy the html structure, and is often used in the scene of public code block extraction. Highest priority: order=1
  6. th:fragment : Define a code block for easy reference by th:insert. Lowest priority: order=8
  7. th:object : Declare variables, generally used together with *{} to achieve the effect of laziness. General priority: order=4
  8. th:attr : modify any attribute, it is rarely used in actual development, because there are abundant other th attributes to help, similarly there are th:attrappend, th:attrprepend. General priority: order=5

When using Thymeleaf attributes, you need to pay attention to the following five points: 

  1. To use Thymeleaf syntax, first declare the namespace: xmlns:th="http://www.thymeleaf.org "
  2. Set text content th:text, set input value th:value, loop output th:each, conditional judgment th:if, insert code block th:insert, define code block th:fragment, declare variable th:object
  3. The usage of th:each needs special attention. For example: if you want to loop the p tag in a div, the th:each attribute must be placed on the p tag. If you put the th:each attribute on the div, the loop will be the entire div.
  4. Many built-in methods are provided in variable expressions, which start with #, please do not confuse them with #{} message expressions.
  5. th:insert, th:replace, and th:include have similar effects for inserting code blocks, but they are very different.

If the page reference expression variable reports a red warning, introduce the following code into the page header

<!--suppress ThymeleafVariablesResolveInspection -->

   4.2.2 Practical operation

  • controller 
package com.jmh.springthymeleaf.conyroller;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 蒋明辉
 * @data 2022/11/15 8:41
 */
@Controller
public class IndexConytroller {
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    class Dog{
        String id;
        String name;
        String sex;
        int age;
    }

    @RequestMapping("/")
    public ModelAndView index(){
        //实例对象modelAndView
        ModelAndView modelAndView=new ModelAndView();
        //1.将字符串保存到作用域里面
        modelAndView.addObject("name","蒋明辉");
        modelAndView.addObject("uname","蒋明辉是个大帅比");
        //2.将对象保存到作用域里面
        modelAndView.addObject("dog",new Dog("1","旺财","公",8));
        //3.将对象集合保存到作用域里面
        List<Dog> dogs=new ArrayList<>();
        dogs.add(new Dog("1","旺财","公",18));
        dogs.add(new Dog("2","来福","公",28));
        dogs.add(new Dog("3","许杰","母",38));
        modelAndView.addObject("dogs",dogs);
        //4.将map集合保存到作用域里面
        Map<String,Object> map=new HashMap<>();
        map.put("Boss",new Dog("1","旺财","公",8));
        modelAndView.addObject("map",map);
        //5.绑定一个字符串
        modelAndView.addObject("itdragonStr","this is a DEMO");
        //跳转视图
        modelAndView.setViewName("index");
        return modelAndView;
    }
}
  •  html
<!DOCTYPE html>
<!--suppress ThymeleafVariablesResolveInspection -->
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>首页</title>
</head>
<body>
<h1>springboot整合thymeleaf模板引擎</h1>
<!--th:text 设置当前元素的文本内容,常用,优先级不高-->
<p th:text="${name}"></p>
<p th:text="${uname}"></p>
<!--th:value 设置当前元素的value值,常用,优先级仅比th:text高-->
姓名: <input th:value="${dog.name}">
年龄: <input th:value="${dog.age}">
性别: <input th:value="${dog.sex}">
<hr/>
<!--th:each 遍历列表,常用,优先级很高,仅此于代码块的插入,遍历被修饰的元素-->
<table border="1px" th:width="200px">
    <thead>
    <tr>
        <th>编号</th>
        <th>姓名</th>
        <th>年龄</th>
        <th>性别</th>
        <th>操作</th>
    </tr>
    <tbody>
    <tr th:each="e,eState:${dogs}">
        <td th:text="${eState.index+1}"></td>
        <td th:text="${e.name}"></td>
        <td th:text="${e.age}"></td>
        <td th:text="${e.sex}"></td>
        <td>删除/修改</td>
    </tr>
    </tbody>
    </thead>
</table>
<br/>
<!--th:if 条件判断,类似的有th:switch,th:case,优先级仅次于th:each,-->
<p th:text="${map.Boss.name}" th:if="${map.Boss.age gt 1}"></p>
...
<!--在html中使用内置方法:-->
<h3>#strings </h3>
<div th:if="${not #strings.isEmpty(itdragonStr)}" >
    <p>Old Str : <span th:text="${itdragonStr}"/></p>
    <p>toUpperCase : <span th:text="${#strings.toUpperCase(itdragonStr)}"/></p>
    <p>toLowerCase : <span th:text="${#strings.toLowerCase(itdragonStr)}"/></p>
    <p>equals : <span th:text="${#strings.equals(itdragonStr, 'itdragonblog')}"/></p>
    <p>equalsIgnoreCase : <span th:text="${#strings.equalsIgnoreCase(itdragonStr, 'itdragonblog')}"/></p>
    <p>indexOf : <span th:text="${#strings.indexOf(itdragonStr, 'r')}"/></p>
    <p>substring : <span th:text="${#strings.substring(itdragonStr, 2, 8)}"/></p>
    <p>replace : <span th:text="${#strings.replace(itdragonStr, 'it', 'IT')}"/></p>
    <p>startsWith : <span th:text="${#strings.startsWith(itdragonStr, 'it')}"/></p>
    <p>contains : <span th:text="${#strings.contains(itdragonStr, 'IT')}"/></p>
</div>
...
</body>
</html>
  •  Practical effect

Guess you like

Origin blog.csdn.net/m0_63300795/article/details/127861204