Using the Thymeleaf template of SpringBoot

Using the Thymeleaf template of SpringBoot

introduce

When developing traditional Java WEB projects, we can use JSP page template language, but it is not recommended in SpringBoot. SpringBoot supports the following page template languages

Thymeleaf

FreeMarker

Velocity

Groovy

JSP

The above does not list all the page template technologies supported by SpringBoot. Thymeleaf is officially recommended by SpringBoot. Let's talk about some common syntax rules of thymeleaf.

Thymeleaf's default page file suffix is. html

Why Thymeleaf?

In short, Thymeleaf is a template engine similar to Velocity and FreeMarker, which can completely replace JSP. Compared with other template engines, it has the following four attractive features:

Dynamic and static combination: thymeleaf can run in both network and non network environments, that is, it allows artists to view the static effect of the page in the browser and programmers to view the dynamic page effect with data in the server. This is because it supports html prototypes, and then adds additional attributes in html tags to achieve the presentation of template + data. When the browser interprets html, it ignores undefined tag attributes, so the thymeleaf template can run statically; When data is returned to the page, the thymeleaf tag will dynamically replace the static content to make the page display dynamically.

In this way, the so-called dynamic and static combination can only show the effect of the front end during development. If Thymeleaf tag syntax is added to the tag, the value used in the html tag will be replaced with the value passed by the back end

Out of the box: you can directly apply templates to achieve the effect of JSTL and OGNL expressions, avoiding the trouble of setting templates, changing JSTL and changing labels every day. At the same time, developers can also extend and create custom dialects.

Multi dialect support: Thymeleaf provides spring standard dialect and an optional module perfectly integrated with spring MVC, which can quickly realize form binding, Attribute Editor, internationalization and other functions.

It is perfectly integrated with SpringBoot. SpringBoot provides the default configuration of Thymeleaf, and sets a view parser for Thymeleaf. We can operate Thymeleaf like we used to operate JSPS. There is almost no difference between the code and the template syntax.

use

Next, we will experience the charm of Thymeleaf through an introductory case

Add Thymeleaf dependency in pom.xml

<!--        template engine  -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
            <version>2.2.2.RELEASE</version>
		</dependency>

SpringBoot will automatically register a view parser for Thymeleaf:

We also need to create templates (fixed name) in resources, which is the fixed template storage place of Springboot

Static is the static resource access path of SpringBoot. If you don't understand it, you can find SpringBoot accessing static resources.md in my blog

When accessing, just like the view parser in spring MVC, use Model or ModelAndView... To pass values

Default prefix: classpath:/templates/

Default suffix:. html

So if we return to the view: users, we will point to classpath:/templates/users.html

Generally, we do not need to modify it. It can be modified by default.

Note: pages that use templates template syntax must be placed in the templates directory before they can be parsed, otherwise they cannot be parsed

The pages in the templates can only be accessed through the parser, that is, the interface needs to be written in the Controller, and then jump through the interface

Small case

Omit the database connection operation and Serivce... Just add it yourself

Create Controller

package cn.boke.controller;

import cn.boke.entity.User;
import cn.boke.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.util.List;

@RestController
public class MapperController {
    
    @Resource(name = "UserServiceImpl")
    private UserService userService;

    @RequestMapping("/queryUser")
	public  ModelAndView queryUser() {
		//Query all the User table data from the database and return to the page
        List<User> users = userService.queryAll();
        ModelAndView mode=new ModelAndView();
        mode.addObject("users",users);
        mode.setViewName("users");
        return mode;
    }

}

Create template

Notice that: xmlns:th is added to the html namespace=“ http://www.thymeleaf.org ”There will be syntax prompts

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" lang="ch">
<head>
       <meta charset="UTF-8">
       <title>home page</title>
       <style type="text/css">
           table {border-collapse: collapse; font-size: 14px; width: 80%; margin: auto}
           table, th, td {border: 1px solid darkslategray;padding: 10px}
       </style>
</head>
<body>
<div style="text-align: center">
       <span style="color: darkslategray; font-size: 30px">Welcome!</span>
       <hr/>
       <table >
           <tr>       
               <th>full name</th>
               <th>password</th>        
           </tr>
           <tr th:each="user : ${users}">
               <td th:text="${user.username}">Hu 123</td>
               <td th:text="${user.password}">123456789</td>        
           </tr>
       </table>

</div>


</body>
</html>

We see that the following syntax is used here:

th is the abbreviation of thymeleaf

${}: This is similar to the el expression

th:each: similar to c:foreach traversing a collection, but the syntax is more concise

th:text: text in the declaration label

More syntax will be dedicated to writing a document. Here is a simple demonstration of how to use it

Let's start the test http://localhost/queryUser

Thymeleaf will cache the template after it is parsed for the first time, which greatly improves the concurrent processing ability. However, this brings inconvenience to our development. We will not see the effect immediately after modifying the page. We can turn off the cache in the development stage:

If you use application.yml, add it to the file

spring:
# In the development phase, close the template cache of thymeleaf, otherwise you need to restart the boot every time you modify it    
  thymeleaf:
 	cache: false

After setting, every time you need to display the latest data, press and hold shift+ctrl +F9 in the IDEA to start the update. You don't need to restart the boot

If you are using application.properties, add it to the file

#Turn off thymeleaf's template cache during development

spring.thymeleaf.cache=false

(# ^. ^ #) it's helpful for you. Click the reward below to see how much it means. It depends on your mood *If you are using application.properties, add it to the file**

#Turn off thymeleaf's template cache during development

spring.thymeleaf.cache=false

Like - collect - pay attention Easy to review and receive the latest content in the future If you have other questions to discuss in the comment area - or send me a private letter - you will reply as soon as you receive them Thank you for your cooperation. I hope my efforts will be helpful to you^_^

Tags: Java Front-end Spring Boot Thymeleaf html

Posted on Sun, 19 Sep 2021 12:50:34 -0400 by wudiemperor