“This is the 13th day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021”

In the project development before and after the end of the separation specification today, back-end development no longer need to carry out page development, but as Java developers must be no stranger to JSP, which is also a big weapon of early Web development.

Thymeleaf can be said to be an upgraded version of JSP. It can not only be perfectly supported by SpringBoot as a template for page development, but also the template format is HTML file, so that static pages are no longer dependent on the server, can be directly opened in the browser to view the effect.

Thymeleaf, as a template for back-end page development, avoids cross-domain problems caused by the separation of the front and back ends, and enables rapid development iterations for simple pages such as background management. Learn about Thymeleaf and first see how you can integrate Thymeleaf into your SpringBoot project.

1. Create a SpringBoot project

1.1 Select the starting dependency

When creating a SpringBoot project, there are a number of dependencies to start with, including the Thymeleaf launcher. In Template Engines, select the Thymeleaf launcher.

Check it and click Next to complete project creation.

1.2 Manually Adding a Dependency

If the associated Thymeleaf initiator was not selected when the project was created, you can add the Thymeleaf dependency information to maven’s coordinate configuration pop.xml file.

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

Once created, you have a SpringBoot project that integrates Thymeleaf, structurally similar to a normal project, but with a templates folder in the Resources folder where the Thymeleaf template files are stored.

2. The Thymeleaf configuration

2.1 SpringBoot automatically configures Thymeleaf

SpringBoot framework provides the Thymeleaf template engine automatic loading configuration, automatic configuration in SpringBoot class package, there is a org. Springframework. Boot. Autoconfigure. Thymeleaf package, The ThymeleafProperties class defined is thymeleaf’s auto-configuration class, which specifies some of the thymeleaf framework’s default properties, such as the template’s default path prefix classpath:/templates/, and the template file format suffix.html.

The ThymeleafProperties class is partially defined as follows:

// Automatic configuration class ThymeleafProperties
@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

As you can see, the configuration class reads the configuration content prefixed with Spring.thymeleaf in the SpringBoot configuration file. Therefore, if you need to customize the configuration of Thymeleaf, you only need to specify it in the application.properties file.

2.2 User-defined Configuration Items

The ThymeleafProperties class is initialized to read the contents of the application. Properties file. The thymeleaf configuration items that can be defined in the configuration file are:

# prefix thymeleaf template file, you can customize the folder as the classpath: / templates/temp
spring.thymeleaf.prefix=classpath:/templates/
The # thymeleaf template file suffix
spring.thymeleaf.suffix=.html
View template type
spring.thymeleaf.mode=HTML
The default view encoding format
spring.thymeleaf.encoding=UTF-8 
# response type
spring.thymeleaf.servlet.content-type=text/html
Thymeleaf is enabled by default. The page cannot be refreshed in time, so it needs to be disabled
spring.thymeleaf.cache=false
Copy the code

The thymeleaf template engine can be used more effectively by customizable configuration values.

3. Thymeleaf page effect

Now that the project is created and the configuration is added, let’s take a look at what thymeleaf brings to the page.

3.1 Defining HTML files

To display a page using the Thymeleaf template engine, start by creating an HTML file and binding it to the interface data according to thymeleaf syntax encoding.

  • When defining an HTML file, use the<html>Label usexmlns:th="http://www.thymeleaf.org"Declaration so thymeleaf syntax can be used in the current HTML page.
  • For the collection of data returned by the service interface binding, you can useth:each="user : ${userEntityList}"Iterate over the corresponding values
  • For the value of each attribute, use theth:text="${user.getName()}"To get the display
<! DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Insert title here</title> < / head > < body > < table > < thead > < tr > < th > name < / th > < th > gender < / th > < th > call < / th > < / tr > < thead > < tbody > < tr th: each = "user: ${userEntityList}"> <td th:text="${user.getName()}">name</td> <td th:text="${user.getGender()}">male</td> <td th:text="${user.getPhone()}">13812341234</td> </tr> </tbody> </table> </body> </html>Copy the code

3.2 Defining service Interfaces

Define the service interface to pass data to the Thymeleaf template. Note when defining the interface:

  • The @Controller annotation is used instead of @RestController, so @RestController parses the result and displays the string instead of getting the template name based on the string
  • The service interface needs to add Model objects as parameters and use the Model objects to bind the data that needs to be passed for use in Thymeleaf
@Controller public class ThymeleafController { @RequestMapping("/index") public String getIndex(Model model){ List<UserEntity> userList = new ArrayList<>(); UserEntity user = new UserEntity("tom","female", "17788996600"); userList.add(user); model.addAttribute(userList); return "index"; }}Copy the code

3.3 Page Display

After doing so, you can run the project and request the defined service interface, which adds the data to the Model and finds the corresponding Thymeleaf template file based on the results returned by the interface, rendering the data in the template file and finally displaying it on the page.