在处理模板时,可以由模板逻辑决定是否加载数据,以提高性能。
在Spring Boot控制器中设置数据时,使用LazyContextVariable可以实现这功能。
开发环境:IntelliJ IDEA 2019.2.2
Spring Boot版本:2.1.8
新建一个名称为demo的Spring Boot项目。
1、pom.xml
加入Thymeleaf依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
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<User> queryUsers(){
  System.out.println("模拟查询数据,实际应用中可以直接查询数据库");
  List<User> users = new ArrayList<User>();
  users.add(new User(1,"张三"));
  users.add(new User(2,"李四"));
  users.add(new User(3,"王五"));
  return users;
 }
}
4、src/main/resources/templates/test.html
<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>Title</title>
 <style type="text/css">
  table { border-collapse:collapse;}
  td { border: 1px solid #C1DAD7;}
 </style>
</head>
<body>
 <table th:if="${show == true}">
  <tr th:each="user : ${users}">
   <td th:text="${user.id}"></td>
   <td th:text="${user.name}"></td>
  </tr>
 </table>
</body>
</html>
浏览器访问:
http://localhost:8080/false ,页面没显示数据,控制台没输出信息。
http://localhost:8080/true ,页面显示数据,控制台输出"模拟查询数据,实际应用中可以直接查询数据库”。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。