Thymeleaf常用语法:数据延迟加载

在处理模板时,可以由模板逻辑决定是否加载数据,以提高性能。
在Spring Boot控制器中设置数据时,使用LazyContextVariable可以实现这功能。

开发环境:IntelliJ IDEA 2019.2.2
Spring Boot版本:2.1.8

新建一个名称为demo的Spring Boot项目。

1、pom.xml
加入Thymeleaf依赖

        
            org.springframework.boot
            spring-boot-starter-thymeleaf
        


2、src/main/java/com/example/demo/user.java

package com.example.demo;

public class User {
    Integer id;
    String name;

    public User(Integer id, String name) {
        this.id = id;
        this.name = name;
    }
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

3、src/main/java/com/example/demo/TestController.java

package com.example.demo;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.thymeleaf.context.LazyContextVariable;

import java.util.ArrayList;
import java.util.List;

@Controller
public class TestController {
    @RequestMapping("/{show}")
    public String test(Model model, @PathVariable("show") boolean show){
        model.addAttribute("users", new LazyContextVariable() {
            @Override
            protected Object loadValue() {
                return queryUsers();
            }
        });
        model.addAttribute("show", show);
        return "test";
    }

    private List queryUsers(){
        System.out.println("模拟查询数据,实际应用中可以直接查询数据库");
        List users = new ArrayList();
        users.add(new User(1,"张三"));
        users.add(new User(2,"李四"));
        users.add(new User(3,"王五"));
        return users;
    }
}

4、src/main/resources/templates/test.html




    
    Title
    


    

浏览器访问:
http://localhost:8080/false ,页面没显示数据,控制台没输出信息。
http://localhost:8080/true ,页面显示数据,控制台输出"模拟查询数据,实际应用中可以直接查询数据库”。

你可能感兴趣的:(SpringBoot2学习笔记)