[Spring Boot] Thymeleaf Template Engine - Getting Started with Thymeleaf

Getting Started with Thymeleaf

It mainly introduces what is Thymeleaf and how Spring Boot integrates and uses Thymeleaf templates, and finally introduces some common configuration parameters of Thymeleaf supported by Spring Boot.

Introduction to Thymeleaf

Thymeleaf is a very good server-side page template engine, suitable for Web and stand-alone environments, with rich tag language and functions, capable of processing HTML, XML, JavaScript and even text.

Thymeleaf is more elegant than other template engines. It emphasizes natural templating (allowing templates to become working prototypes, while Velocity, FreeMarker templates do not allow this), so its syntax is cleaner and more in line with current web development trends.

1. Implementation mechanism of Thymeleaf

Templates were born to separate display from data. There are various template technologies, the essence of which is to pass template files and data through a template engine to generate the final HTML code.

The same goes for Thymeleaf. Thymeleaf injects its logic into the template control without affecting the template design prototype, so HTML pages and data can be displayed correctly in the browser, and can also be displayed statically when there is no background. Since the Thymeleaf template suffix is ​​.html, it can be opened directly in the browser, and the preview is very convenient. This improves designer-developer communication and bridges the gap between designers and development teams, allowing for stronger collaboration within the development team.

2. Advantages of Thymeleaf

Thymeleaf is similar to template engines such as Velocity and FreeMarker, and can completely replace JSP. Compared with other template engines, Thymeleaf has the following advantages:

1) Combination of static and dynamic: The Thymeleaf page adopts the display method of template + data, which can not only display static pages, but also display the dynamic effect after the data returns to the page. This is because Thymeleaf supports HTML prototypes, and additional attributes can be added to HTML prototypes. Browsers ignore undefined attributes when interpreting HTML. When defined attributes contain data, they will dynamically replace static content to achieve dynamic page display.

2) Out of the box: Thymeleaf provides standard dialects and Spring dialects, which can directly apply templates to achieve JSTL and OGNL expression effects, avoiding the troubles of setting templates, changing JSTL, and changing labels. At the same time, developers can also extend and create custom dialects.

3) Multi-dialect support: Thymeleaf provides spring standard dialects and an optional module perfectly integrated with Spring MVC, which can quickly implement functions such as form binding, property editor, and internationalization.

4) Perfect integration with Spring Boot: Spring Boot provides the default configuration of Thymeleaf, and sets up a view resolver for Thymeleaf, which can operate Thymeleaf like JSP. There is hardly any difference in code, only in the template syntax.

Spring Boot officially recommends using Thymeleaf as the front-end page template, and Spring Boot 2.0 uses Thymeleaf 3.0 by default. At the same time, Spring Boot also provides spring-boot-starter-thymeleaf components (integrated Thymeleaf template engine) for Thymeleaf, and also supports Thymeleaf automatic assembly, which can be used out of the box.

Thymeleaf using Spring Boot

Spring Boot provides very complete support for Thymeleaf, making it very simple for us to use Thymeleaf, just import the spring-boot-starter-thymeleaf dependency library. The following is a simple example to demonstrate how Spring Boot integrates Thymeleaf.

Step 01 Add Thymeleaf dependency.

Modify the pom.xml file of the project and add spring-boot-starter-thymeleaf dependency configuration:

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

In the above example, in addition to the spring-boot-starter-thymeleaf dependency library, components such as spring-boot-starter-web and spring-boot-starter need to be introduced in the Spring Boot project.

Step 02 Configure Thymeleaf parameters.

If you need to customize the default Thymeleaf configuration parameters, you can configure and modify them directly in application.properties:

#是否开启缓存,开发时可以设置为false,默认为true
spring.thymeleaf.cache=false
#模板文件位置
spring.thymeleaf.prefix=classpath:/templates/
# Content-Type配置
spring.thymeleaf.servlet.content-type=text/html
# 板文件后缀
spring.thymeleaf.suffix=.html

In the above example, it is mainly to configure the storage location of the Thymeleaf template page. Of course, other features of Thymeleaf can also be flexibly configured through application.properties. Among them, spring.thymeleaf.cache=false is used to close the cache of Thymeleaf. Otherwise, modifying the page during the development process will not take effect and needs to be restarted. The production environment can be configured as true.

Step 03 Create a Thymeleaf page.

The suffix of the Thymeleaf template is .html, and the hello.html page is created in the resource\templates template storage directory. The sample code is as follows:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head lang="en">
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
Thymeleaf模板引擎
<h1 th:text="${name}">Hello Thymeleaf</h1>
</body>
</html>

In the above example, we created the hello.html page. This page can be run directly by double-clicking, and the page will display "Hello Thymeleaf".

Step 04 Create a background controller (Controller).

Create a HelloController controller in the Controller directory and implement the test method. The sample code is as follows:

@Controller
public class HelloController {
    
    
    @RequestMapping("/hello")
    public String hello(ModelMap map) {
    
    
        map.addAttribute("name","Hello Thymeleaf From Spring Boot");
        return "hello";
    }
}

In the above example, the @Controller annotation is used to return the page and data. To return the specific hello.html page, it needs to be consistent with the path of the front-end HTML, and return the data name=Hello Thymeleaf.

Step 05 Run the verification.

So far, the preparatory work has been completed. After starting the project, enter the URL http://localhost:8080/hello in the browser to verify whether the Thymeleaf configuration is successful, as shown in the figure.

insert image description here
It can be seen from the figure that the hello.html page is successfully returned, and the default value of the page has been successfully replaced by the content passed in from the backend through the th:text="${name}" tag. It shows that Thymeleaf has been successfully integrated into our Spring Boot project.

Thymeleaf is very simple to use, and the tags are similar to the Html base. However, you need to pay attention to the following issues when using Thymeleaf:

1) The Thymeleaf template page must declare xmlns:th="http://www.thymeleaf.org/ in the HTML tag, indicating that the page uses Thymeleaf syntax, otherwise Thymeleaf's custom tags will not prompt.

2) The template path configured in the application.properties file is classpath:/templates/, and the template storage path is in the resource/templates directory.

3) The default path of Spring Boot to store template pages is in src/main/resources/templates or src/main/view/templates, no matter what template language is used, of course, the default path can be customized, but it is generally not recommended to do so .

4) The default page file suffix of Thymeleaf is .html, which can also be changed to other suffixes.

Thymeleaf commonly used configuration parameters

Thymeleaf provides many customizable configuration parameters, but these Spring Boot has been configured by default. If you need to customize and modify these configurations, you can flexibly configure various features of Thymeleaf through the application.properties configuration file. The following are Thymeleaf configuration and default parameters:

#THYMELEAF (ThymeleafAutoConfiguration)
#开启模板缓存(默认值: true )
spring.thymeleaf.cache=true
#检查模板是否存在,然后呈现
spring.thymeleaf.check-template=true
#检查模板位置是否正确(默认值:true )
spring.thymeleaf.check-template-location=true
#Content-Type的值(默认值: text/html)
spring.thymeleaf.content-type=text/html
#开启MVC Thymeleaf视图解析(默认值: true)
spring.thymeleaf.enabled=true
#模板编码
spring.thymeleaf.encoding=UTF-8
#要被排除在解析之外的视图名称列表,用逗号分隔
spring.thymeleaf.excluded-view-names=
#定义模板的模式(默认值: HTML5)
spring.thymeleaf.mode=HTML5
# 在构建URL时添加到视图名称前的前缀 (默认值: cLasspath:/templates/)
spring.thymeleaf.prefix=classpath:/templates/
# 在构建URL时添加到视图名称后的后缀(默认值: .html )
spring.thymeleaf.suffix=.html
# Thvmeleaf模板解析器在解析器链中的顺序,默认情况下,它排在第一位,顺序从1开始,只有在定义了额外的TempLateResolver Bean时才需要设置这个属性
spring.thymeleaf.template-resolver-order=
#可解析的视图名称列表,用逗号分隔
spring.thymeleaf.view-names=

The above Thymeleaf attribute configurations seem to be many, but in fact, the commonly used configuration items are the configuration items introduced earlier. Other configuration items can be modified according to actual usage in actual projects.

Guess you like

Origin blog.csdn.net/weixin_45627039/article/details/132061222