Getting started with Spring Boot integrating Thymeleaf template engine Thymeleaf

Spring Boot integrates Thymeleaf

image

Introduction to Thymeleaf

  • 1. Thymeleaf is a template engine similar to Velocity and FreeMarker, it can completely replace JSP. Compared with other template engines, it has the following three very attractive features
  • 2. Thymeleaf can run in both networked and non-networked environments, that is, it allows artists to view the static effect of the page in the browser, and also allows the programmer to view the dynamic page effect with data on the server.
  • 3. Thymeleaf features out of the box. It provides two dialects, Standard and Spring Standard, and can directly apply templates to achieve JSTL and OGNL expression effects, avoiding the trouble of setting templates, changing JSTL, and changing tags every day. At the same time, developers can also extend and create custom dialects.

Of course, the Spring Boot page provides a large number of templates including:

  • 1.FreeMarker
  • 2.Groovy
  • 3.Mustache
  • 4. Thymeleaf users are mostly
  • 5.Velocity
  • 6. Beetl's domestic claim is 10 times faster than the one above, but no one uses Beetl
    to add it in the pom.xml file
 <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
 </dependency>
 # 添加nekohtml的目的:为了非严格遵守w3c编程规范
 # 比如 <input /> 必须要有结束符 否则编译报错
  <dependency>
        <groupId>net.sourceforge.nekohtml</groupId>
        <artifactId>nekohtml</artifactId>
        <version>1.9.22</version>
  </dependency>

Configure Thymeleaf in application.yml. The official recommendation is to use configuration files in yaml/yml format.

Introduction to the use of yaml

YAML language (pronounced: Yeah Maiou) The design goal of yml is to make it easier for people to read and write. It is essentially a universal data serialization format.
Its basic grammar rules are as follows.

  • 1. Case sensitive
  • 2. Use indentation to indicate hierarchical relationships
  • 3. Tab key is not allowed when indenting , only spaces are allowed .
  • 4. The number of indented spaces is not important, as long as the elements of the same level are aligned to the left
spring:
  thymeleaf:
    cache: false # 开发时关闭缓存,不然没法看到实时页面
    mode: HTML # 用非严格的 HTML  不加nekohtml依赖的话这个模式用不了 
    encoding: UTF-8
    servlet:
      content-type: text/html   

Test Thymeleaf

  • Create JavaBean User for Testing
@Data //Lombok的注解 自动添加get set toString hashCode 等等基本方法
@Component //把这个bean注册到Spring
public class PersonBean implements Serializable {
    
    

    private String name;
    private Integer age;

}

  • Create a test controller
@Controller
@RequestMapping(value = "thymeleaf")
public class IndexController {

    @RequestMapping(value = "index", method = RequestMethod.GET)
    public String index(Model model) {
        PersonBean person = new PersonBean();
        person.setName("张三");
        person.setAge(22);

        List<PersonBean> people = new ArrayList<>();
        PersonBean p1 = new PersonBean();
        p1.setName("李四");
        p1.setAge(23);
        people.add(p1);

        PersonBean p2 = new PersonBean();
        p2.setName("王五");
        p2.setAge(24);
        people.add(p2);

        PersonBean p3 = new PersonBean();
        p3.setName("赵六");
        p3.setAge(25);
        people.add(p3);

        model.addAttribute("person", person);
        model.addAttribute("people", people);

        return "index";
    }
}
  • Create a test page
  • Create an empty index.html page
  • Type html5 and press Tab
<!DOCTYPE html SYSTEM "http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-spring4-4.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Hello Thymeleaf</title>
</head>
<body>
    <div>
        <span>访问 Model:</span><span th:text="${person.name}"></span>
    </div>
    <div>
        <span>访问列表</span>
        <table>
            <thead>
                <tr>
                    <th>姓名</th>
                    <th>年龄</th>
                </tr>
            </thead>
            <tbody>
                <tr th:each="human : ${people}">
                    <td th:text="${human.name}"></td>
                    <td th:text="${human.age}"></td>
                </tr>
            </tbody>
        </table>
    </div>
</body>
</html>
  • Modify the html tag to introduce the thymeleaf engine, so that the th:* syntax can be used in other tags, and the declaration is as follows:
<!DOCTYPE html SYSTEM "http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-spring4-4.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
  • Test access to SpringBoot Thymeleaf test If the following data appears, the test is successful!
    [External link image transfer failed. The origin site may have an anti-leech link mechanism. It is recommended to save the image and upload it directly (img-1sb711i2-1588560276266)(02F69E2682964569845B93966674C7D3)]
  • testing successfully!

Why does Spring officially recommend the use of yml format configuration files

  • Powerful
  • Can store complex data types "Object array Map, etc...
  • Clear configuration file structure

The yml configuration file configures JavaBean initialization data

  1. Modify the User class to add the following attributes
    private Map<String,Object> hobby; //爱好
    private List<String> pets; //所有宠物
    private boolean ishappy; //是否开心 
  1. Add the following configuration to the yml file
person:
  name: 师文远
  age: 22
  hobby: {
    
    v1:,v2:,v3: rap}
  pets:
    - aa1
    - aa2
    - aa3
  ishappy: true
  1. Add a comment above the User class name
@ConfigurationProperties(value = "person") //与yml中的对象保持一致
  1. Add in the test class
    @Resource
    private User user;
    
    @Test
    public void getUserInfo() {
    
    
        System.out.println(user);
    }
  1. Test Results

Guess you like

Origin blog.csdn.net/weixin_43420255/article/details/105914357