1. The Thymeleaf is introduced
Thymeleaf is a modern server-side Java templating engine for Web and standalone environments. The primary goal of Thymeleaf is to bring elegant natural templates to your development workflow – HTML that can be displayed correctly in a browser or used as a static prototype, enabling greater collaboration across development teams.
The above translation is from Thymeleaf official website. The traditional JSP+JSTL combination is the past, Thymeleaf is a modern server template engine, different from the traditional JSP, Thymeleaf can be directly opened by the browser, because you can ignore the extension attribute, equivalent to open the native page, to the front end personnel also bring certain convenience.
2. Common Grammar
Common expressions
The ${... } : variable expression. * {... } : Select an expression. # {... } : message literal expression. @ {... } : Link URL expression. #maps: tool object expression.Copy the code
Commonly used tags
Th :action: defines the background controller path. Th :each: loop statement. Th :field: form field binding. Th :href: Defines hyperlinks. Th: ID: div tag id declaration, similar to HTML tag attribute. Th :if: indicates the conditional statement. Th :include: layout tag that replaces content into the import file. Th: Fragment: layout tag that defines a code fragment for reference elsewhere. Th :object: replaces the object. Th: SRC: import the image address. Th :text: displays the text. Th :value: indicates that the attribute is assigned.Copy the code
Commonly used functions
#dates: date function. #lists: Lists function. # Arrays: array functions. #strings: string function. #numbers: numbers function. #calendars: calendar function #objects: object functions. #bools: logical functions.Copy the code
Examples: Some common tag operations in Thymeleaf are as follows:
The label | function | example |
---|---|---|
th:value |
Assign a value to an attribute | <input th:value="${blog.name}" /> |
th:style |
Set the style | th:style="'display:'+@{(${sitrue}? 'none':'inline-block')} + ''" |
th:onclick |
Click on the event | th:onclick="'getInfo()'" |
th:if |
conditional | <a th:if="${userId == collect.userId}" > |
th:href |
hyperlinks | <a th:href="@{/blogger/login}">Login</a> /> |
th:unless |
Conditional judgment sumth:if On the contrary |
<a th:href="@{/blogger/login}" th:unless=${session.user ! = null}>Login</a> |
th:switch |
Cooperate withth:case |
<div th:switch="${user.role}"> |
th:case |
Cooperate withth:switch |
<p th:case="'admin'">administator</p> |
th:src |
Address to introduce | <img alt="csdn logo" th:src="@{/img/logo.png}" /> |
th:action |
The address to submit the form | <form th:action="@{/blogger/update}"> |
There are many other uses of Thymeleaf, which are not summarized here. For details, please refer to the official Thymeleaf documentation (V3.0).
3. Rely on imports
Using the Thymeleaf template in Spring Boot requires importing dependencies. Add the following dependencies to the POM file:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
Copy the code
In addition, if you want to use the Thymeleaf template on an HTML page, you need to introduce it in the page tag:
<html xmlns:th="http://www.thymeleaf.org">
Copy the code
4. Configure Thymeleaf
Since Thymeleaf already has the default configuration, we do not need to do too much configuration for it. One thing needs to be noted that Thymeleaf is enabled with page caching by default, so it needs to be disabled during development. The configuration is as follows.
spring:
thymeleaf:
cache: false # disable cache
Copy the code
Otherwise, there will be a cache, resulting in the page cannot see the updated effect in time. For example, if you modify a file and update it to Tomcat, the updated page is the same as the previous page, because of the cache.
5. Use of Thymeleaf
5.1 Accessing a Static Page
When we do a website, we always make a 404 page and a 500 page, to give the user a friendly display when something goes wrong, rather than a bunch of exceptions thrown out. Spring Boot automatically recognizes 404.html and 500.html files in the templates/ directory. We’ll create a new error folder in the Templates/directory, place the wrong HTML pages, and print out the information separately. Take 404.html for example:
<! DOCTYPEhtml>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>404 page of wechat official account [Simcode Tiandi]</body>
</html>
Copy the code
Let’s write another controller to test the 404 and 500 pages:
package com.bowen.controller;
import com.bowen.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.ArrayList;
import java.util.List;
/** * <h3>springboot-study</h3> * <p>thymeleaf test Controller class </p> *@author : zhang.bw
* @date: the 2020-07-17 21:37 * * /
@Controller
@RequestMapping("/thymeleaf")
public class ThymeleafController {
@GetMapping("/test404")
public String test404(a) {
return "index";
}
@GetMapping("/test500")
public String test500(a) {
int i = 1 / 0;
return "index"; }}Copy the code
When we are in the browser enter localhost: 8080 / thymeleaf/test400, intentionally input error, can not find the corresponding method, will jump to 404. The HTML display.
When we are in the browser enter localhost: 8088 / thymeleaf/test505, throws an exception, and then automatically jump to 500. The HTML display.
Note: One thing to note here is that microservices eventually move to the front and back end, and we use the @RestController annotation on the Controller layer, which automatically converts the returned data to JSON format. The Controller layer, however, cannot use the @RestController annotation when using the template engine, because thymeleaf returns the view file name, as in Controller, which returns the index.html page. If you use @restController, you parse the index as a String and return it directly to the page instead of going to the index.html page. So use the @Controller annotation when using a template.
5.2 Objects are processed in Thymeleaf
Let’s look at how object information is handled in the Thymeleaf template. We define a user information entity.
public class User {
private Long id;
private String name;
private String pass;
// omit set and get
}
Copy the code
The user information is then retrieved at the Controller layer and returned to the page.
@GetMapping("/getUser")
public String getUser(Model model) {
User user = new User(1L."Ape Code World."."Monkey Code World");
model.addAttribute("user", user);
return "user";
}
Copy the code
Create a new user.html page to render the data.
<! DOCTYPEhtml>
<html xmlns:th="http://www.thymeleaf.org">
<html lang="en">
<head>
<meta charset="UTF-8">
<title>The customer information</title>
</head>
<body>
<form action="" th:object="${user}" >User No. :<input name="id" th:value="${user.id}"/><br>User Name:<input type="text" name="username" th:value="${user.getName()}" /><br>Login password:<input type="text" name="password" th:value="*{pass}" />
</form>
</body>
</html>
Copy the code
As you can see, in the Thymeleaf template, we use th:object=”${}” to get object information, and then there are three ways to get object attributes in the form. As follows:
Use th:value=”*{attribute name}” use th:value=”${object. Th :value=”${object.get “; th:value=”${object
As you can see, Thymeleaf makes it easy to write code just like Java. We in the browser enter localhost: 8080 / thymeleaf getUser to test the data:
5.3 Process the List in Thymeleaf
Working with a List is similar to working with the objects described above, but requires traversal in Thymeleaf. Let’s first simulate a List in the Controller.
@GetMapping("/getList")
public String getList(Model model) {
User user1 = new User(1L."Monkey Code World 1"."Monkey Code Tiandi 1");
User user2 = new User(2L."Ape Code 2"."Monkey Code Tiandi 2");
List<User> list = new ArrayList<>();
list.add(user1);
list.add(user2);
model.addAttribute("list", list);
return "list";
}
Copy the code
Next we write a list.html to get the list information, and then iterate through the list in list.html. As follows:
<! DOCTYPEhtml>
<html xmlns:th="http://www.thymeleaf.org">
<html lang="en">
<head>
<meta charset="UTF-8">
<title>The customer information</title>
</head>
<body>
<form action="" th:each="user : ${list}" >User No. :<input name="id" th:value="${user.id}"/><br>User Name:<input type="text" name="password" th:value="${user.name}"/><br>Login Password:<input type="text" name="username" th:value="${user.getPass()}"/>
</form>
</body>
</html>
Copy the code
Thymeleaf uses th:each to iterate. ${} takes the parameters passed in the model and then customizes each object retrieved from the list. You can use the ${object directly inside the form. You can also use ${object.get method} to get the value of the object in the list. This is the same as above, but you cannot use *{attribute name} to get the value of the object. The Thymeleaf template does not get the value.
6. Summary
Thymeleaf is widely used in Spring Boot. In this lesson, we will explain how to integrate and use the Thymeleaf template in Spring Boot, including dependencies, configuration, data retrieval, and some considerations. At the same time, some commonly used labels in Thymeleaf are also listed, which can be proficiently used and consulted in actual projects. Through this course, I believe I have a deeper understanding of the use of template engines.
7. Source code acquisition
I am ape man, share technology, taste life, thank you for your likes, favorites and comments, we will see you next time! The article continues to update, you can wechat search a “monkey code world” first time to read, reply [Springboot] to obtain the complete source code.