妖夜奇谭,pk10助赢,褴褛的鬼雾衬肩
在处理模板时,可以由模板逻辑决定是否加载数据,以提高性能。
在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 ,页面显示数据,控制台输出"模拟查询数据,实际应用中可以直接查询数据库”。
如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复
浅析我对 String、StringBuilder、StringBuffer 的理解
使用IDEA搭建SSM框架的详细教程(spring + springMVC +MyBatis)
Springboot整合freemarker 404问题解决方案
引入mybatis-plus报 Invalid bound statement错误问题的解决方法
网友评论