如何使用Thymeleaf给web项目中的网页渲染显示动态数据?(三)

简介: 如何使用Thymeleaf给web项目中的网页渲染显示动态数据?(三)

7.8.2 稍微复杂的对象

案例:创建一个Employee002类,但是Employee02类中将一个Computer类作为自己的成员属性,在请求域内共享Employee002类的对象emp02,rootServlet调用Thymeleaf渲染root.html并响应给客户端,root.html要显示动态数据(请求域内的稍微复杂的对象emp02)

代码演示如下:

//创建Employee02类
public class Employee02 {
    private Integer id;
    private String name;
    private Integer gender; //0 男  1 女
    private Double salary;
    private Computer computer;//对象关联
    public Employee02(Integer id, String name, Integer gender, Double salary, Computer computer) {
        this.id = id;
        this.name = name;
        this.gender = gender;
        this.salary = salary;
        this.computer = computer;
    }
    public Employee02() {
    }
    @Override
    public String toString() {
        return "Employee02{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", gender=" + gender +
                ", salary=" + salary +
                ", computer=" + computer +
                '}';
    }
    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;
    }
    public Integer getGender() {
        return gender;
    }
    public void setGender(Integer gender) {
        this.gender = gender;
    }
    public Double getSalary() {
        return salary;
    }
    public void setSalary(Double salary) {
        this.salary = salary;
    }
    public Computer getComputer() {
        return computer;
    }
    public void setComputer(Computer computer) {
        this.computer = computer;
    }
}
//创建Computer类 
public class Computer {
    private Integer id;
    private String brand;
    private double price;
    public Computer() {
    }
    @Override
    public String toString() {
        return "Computer{" +
                "id=" + id +
                ", brand='" + brand + '\'' +
                ", price=" + price +
                '}';
    }
    public Computer(Integer id, String brand, double price) {
        this.id = id;
        this.brand = brand;
        this.price = price;
    }
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getBrand() {
        return brand;
    }
    public void setBrand(String brand) {
        this.brand = brand;
    }
    public double getPrice() {
        return price;
    }
    public void setPrice(double price) {
        this.price = price;
    }
}
//在rootServle中创建一个employee02对象,渲染root.html后响应给客户端
Employee02 employee02=new Employee02(102,"熊二",1,34567d,new Computer(1,"联想",5000.0)
//请求域内共享一个稍微复杂的对象
request.setAttribute("emp02",employee02);
//调用Thymeleaf渲染root.html页面,响应给客户端
 this.processTemplate("root",request,response);
//root.html获取请求域内emp02的相关属性
复杂对象:
<div th:text="${emp02}"></div>
<div th:text="${emp02.id}"></div>
<div th:text="${emp02.name}"></div>
<div th:text="${emp02.salary}"></div>
Kdiv th:text="${emp02.computer}"></div>
//调用的是emp02的电脑对象的getId()的返回值,下同
<div th:text="{emp02.computer.id}"></div>
<div th:text="$emp02.computer.brand}"></div>
<div th:text="$empe2.computer.price}"></div>

7.8.3 list集合(简单集合)

案例:在请求域内共享list集合,rootServlet调用Thymeleaf渲染root.html网页并响应给客户端,root.html要显示动态数据(请求域内的list集合)

代码演示如下:

//请求域内共享一个list集合
List<String> strs=new ArrayList<>();
strs.add("法外狂徒张三");
strs.add("法外狂徒李四");
strs.add("法外狂徒王五");
request.setAttribute("strs",strs);
//调用Thymeleaf渲染root.html并响应给客户端
this.processTemplate("root",request,response);
<p>list集合</p>
<p th:text="${strs}"></p>
//从请求域中获取list集合strs中下标为0的元素(第0+1个元素),下同
<p th:text="${strs[0]}"></p>
<p th:text="${strs[1]}"></p>
<p th:text="${strs[2]}"></p>

7.8.4 复杂集合(list集合存储对象)

案例:在请求域内共享复杂集合,集合内放三个Employee类的对象,rootServlet调用Thymeleaf渲染root.html,在root.html中要显示动态数据(请求域内的复杂集合)

代码示例如下:

//请求域内共享复杂集合
List<Employee> emps=new ArrayList<>();
emps.add(new Employee(101,"法外狂徒张三",0,500000.0));
emps.add(new Employee(102,"法外狂徒李四",1,68787.0));
emps.add(new Employee(103,"法外狂徒王五",1,198687.0));
request.setAttribute("emps",emps);
//调用Thymeleaf渲染root.html并响应给客户端
this.processTemplate("root",request,response);
<p>复杂集合</p>
<p th:text="${emps}"></p>
//获取集合中第一个对象的toString()的返回值
<p th:text="${emps[0]}"></p>
//获取集合中第一个对象的getId()的返回值
<p th:text="${emps[0].id}"></p>
//获取集合中第一个对象的getName()的返回值
<p th:text="${emps[0].name}"></p>

总结:

遇到对象就通过.属性名的方式去获取属性值(原理是调用get方法)

遇到Lst集合就通过下标获得到元素,如果元素是对象的话,还是回到上一句

7.8.5 复杂集合(map集合存储对象)

遇到Map集合就通过.key值的方式获得value值,如果value值是对象的话,遇到对象就通过.属性名的方式去获取属性值(原理是调用get方法)

案例:请求域内共享map集合,rootServlet调用Thymeleaf渲染root.html后响应给客户端,root.html要显示动态数据(请求域内的map集合)

代码示例如下:

//请求域内共享map集合
Map<String,Employee> map=new HashMap<>();
map.put("emp01",new Employee(101,"法外狂徒张三",0,500000.0));
map.put("emp02",new Employee(102,"法外狂徒李四",1,68787.0));
map.put("emp03",new Employee(103,"法外狂徒王五",1,198687.0));
request.setAttribute("map",map);
//调用Thymeleaf渲染root.html并响应给客户端
this.processTemplate("root",request,response);
<p>map集合</p>
<p th:text="${map}"></p>
//获取请求域内map集合的key值为emp01的value值
<p th:text="${map.emp01}"></p>
//获取请求域内map集合的key值为emp01的value值(对象)的getId()的返回值,下同
<p th:text="${map.emp01.id}"></p>
<p th:text="${map.emp02.name}"></p>

7.9 分支与迭代

7.9.1 分支,控制元素的是否显示

7.9.1.1 th:if 和 th:unless

语法:

th:if="" : 值如果是true,元素就显示,值如果是false,就不显示

th:unless="" : 和if反过来即可

案例:请求域内共享msg数据,调用Thymeleaf渲染页面并呼应给客户端,页面内使用h:if

或th:unless等渲染表达式去判断msg数据的长度

代码示例如下:

//在请求域中共享msg数据   
 request.setAttribute("msg","这是msg数据");
 this.processTemplate("toif",request,response);
<p>th:if/unless</p>
<p th:text="${msg}"></p>
<p th:if="${#strings.length(msg)>5}">msg的数据长度大于5就显示</p>
<p th:if="${#strings.length(msg)<=5}">msg的数据长度小于或等于5就显示(1)</p>
<p th:unless="${#strings.length(msg)>5}">msg的数据长度小于或等于5就显示(2)</p>
<p th:unless="${not (#strings.length(msg)<=5)}">msg的数据长度小于或等于5就显示(3)</p>

7.9.1.2 th:switch和th:case

语法:

th:switch=“” (看switch中的数据和哪个case相同,有相同的就显示哪个)

th:case=“”

案例:请求域内共享msg数据,调用Thymeleaf渲染页面并呼应给客户端,页面内使用渲染表达式th:switch和th:case去判断msg数据的长度并显示结果

代码示例如下:

request.setAttribute("msg","这是msg");
this.processTemplate("toif",request,response);
<div th:switch="${#strings.length(msg)}">
    <p th:case="1">长度为1</p>
    <p th:case="2">长度为2</p>
    <p th:case="3">长度为3</p>
    <p th:case="4">长度为4</p>
    <p th:case="5">长度为5</p>
</div>

7.9.2 迭代(遍历循环)

语法:

th:each=“obj,status:后台请求域中数据的key”

7.9.2.1 简单数组迭代

案例:请求域内共享一个list集合,调用thymeleaf渲染页面并响应给客户端,页面使用渲染表达式th:each去遍历请求域内list集合,在无序列表中显示

代码示例如下:

//请求域内共享一个list集合
List<String> strs=new ArrayList<>();
strs.add("法外狂徒张三");
strs.add("法外狂徒李四");
strs.add("法外狂徒王五");
request.setAttribute("strs",strs);
//迭代从请求域获得的list集合strs,并在无序列表中显示
<ul>
    <li th:each="str,status :${strs}" th:text="${str}"></li>

7.9.2.2 复杂数组迭代

案例:请求域内共享一个list集合(装三个Employee类的对象),调用thymeleaf渲染页面并响应给客户端,页面使用渲染表达式th:each去遍历请求域内的list集合,在表格中显示

//请求域内共享复杂集合
List<Employee> emps=new ArrayList<>();
emps.add(new Employee(101,"法外狂徒张三",0,500000.0));
emps.add(new Employee(102,"法外狂徒李四",1,68787.0));
emps.add(new Employee(103,"法外狂徒王五",1,198687.0));
request.setAttribute("emps",emps);
<table border="1" width="300px">
    <tr>
        <td>序号</td>
        <th>编号</th>
        <th>姓名</th>
        <th>性别</th>
        <th>工资</th>
    </tr>
    <tr th:each="emp,status :${emps}">
        <!--  status.index是从0开始的      -->
        <td th:text="${status.index+1}"></td>
        <td th:text="${emp.id}"></td>
        <td th:text="${emp.name}"></td>
      <!--  
    <td th:if="${emp.gender==0}" th:text="男"></td>
        <td th:if="${emp.gender==1}" th:text="女"></td>
    -->
        <td th:text="${emp.gender==0?'男':'女'}"></td>
        <td th:text="${emp.salary}"></td>
    </tr>
</table>

7.10 Thymeleaf包含其他模板文件

7.10.1 应用场景

网页内公共代码片段的提取

公共代码片段是什么?

以腾讯视频 pc端为例,无论用户点击了什么频道,网站左侧的红框部分总是在那里,不会改变



相关文章
|
8天前
|
网络协议 Java Shell
java spring 项目若依框架启动失败,启动不了服务提示端口8080占用escription: Web server failed to start. Port 8080 was already in use. Action: Identify and stop the process that’s listening on port 8080 or configure this application to listen on another port-优雅草卓伊凡解决方案
java spring 项目若依框架启动失败,启动不了服务提示端口8080占用escription: Web server failed to start. Port 8080 was already in use. Action: Identify and stop the process that’s listening on port 8080 or configure this application to listen on another port-优雅草卓伊凡解决方案
40 7
|
3月前
|
缓存 JSON 监控
如何在项目中保证 Web 组件化的性能
保证 Web 组件化的性能需要从多个方面入手,综合运用各种优化方法和策略。通过持续的优化和改进,能够提高组件化的整体性能,为用户提供更好的体验,同时也有助于提高项目的开发效率和质量。
60 8
|
3月前
|
存储 前端开发 JavaScript
如何在项目中高效地进行 Web 组件化开发
高效地进行 Web 组件化开发需要从多个方面入手,通过明确目标、合理规划、规范开发、加强测试等一系列措施,实现组件的高效管理和利用,从而提高项目的整体开发效率和质量,为用户提供更好的体验。
55 7
|
3月前
|
中间件 Go API
Go语言中几种流行的Web框架,如Beego、Gin和Echo,分析了它们的特点、性能及适用场景,并讨论了如何根据项目需求、性能要求、团队经验和社区支持等因素选择最合适的框架
本文概述了Go语言中几种流行的Web框架,如Beego、Gin和Echo,分析了它们的特点、性能及适用场景,并讨论了如何根据项目需求、性能要求、团队经验和社区支持等因素选择最合适的框架。
228 1
|
3月前
|
监控 安全 测试技术
如何在实际项目中应用Python Web开发的安全测试知识?
如何在实际项目中应用Python Web开发的安全测试知识?
118 61
|
3月前
|
XML 前端开发 JavaScript
PHP与Ajax在Web开发中的交互技术。PHP作为服务器端脚本语言,处理数据和业务逻辑
本文深入探讨了PHP与Ajax在Web开发中的交互技术。PHP作为服务器端脚本语言,处理数据和业务逻辑;Ajax则通过异步请求实现页面无刷新更新。文中详细介绍了两者的工作原理、数据传输格式选择、具体实现方法及实际应用案例,如实时数据更新、表单验证与提交、动态加载内容等。同时,针对跨域问题、数据安全与性能优化提出了建议。总结指出,PHP与Ajax的结合能显著提升Web应用的效率和用户体验。
84 3
|
3月前
|
JavaScript 前端开发 开发工具
web项目规范配置(husky、eslint、lint-staged、commit)
通过上述配置,可以确保在Web项目开发过程中自动进行代码质量检查和规范化提交。Husky、ESLint、lint-staged和Commitlint共同作用,使得每次提交代码之前都会自动检查代码风格和语法问题,防止不符合规范的代码进入代码库。这不仅提高了代码质量,还保证了团队协作中的一致性。希望这些配置指南能帮助你建立高效的开发流程。
111 5
|
2月前
|
前端开发 安全 JavaScript
2025年,Web3开发学习路线全指南
本文提供了一条针对Dapp应用开发的学习路线,涵盖了Web3领域的重要技术栈,如区块链基础、以太坊技术、Solidity编程、智能合约开发及安全、web3.js和ethers.js库的使用、Truffle框架等。文章首先分析了国内区块链企业的技术需求,随后详细介绍了每个技术点的学习资源和方法,旨在帮助初学者系统地掌握Dapp开发所需的知识和技能。
2025年,Web3开发学习路线全指南
|
3月前
|
开发框架 JavaScript 前端开发
TypeScript 是一种静态类型的编程语言,它扩展了 JavaScript,为 Web 开发带来了强大的类型系统、组件化开发支持、与主流框架的无缝集成、大型项目管理能力和提升开发体验等多方面优势
TypeScript 是一种静态类型的编程语言,它扩展了 JavaScript,为 Web 开发带来了强大的类型系统、组件化开发支持、与主流框架的无缝集成、大型项目管理能力和提升开发体验等多方面优势。通过明确的类型定义,TypeScript 能够在编码阶段发现潜在错误,提高代码质量;支持组件的清晰定义与复用,增强代码的可维护性;与 React、Vue 等框架结合,提供更佳的开发体验;适用于大型项目,优化代码结构和性能。随着 Web 技术的发展,TypeScript 的应用前景广阔,将继续引领 Web 开发的新趋势。
66 2
|
3月前
|
开发框架 搜索推荐 数据可视化
Django框架适合开发哪种类型的Web应用程序?
Django 框架凭借其强大的功能、稳定性和可扩展性,几乎可以适应各种类型的 Web 应用程序开发需求。无论是简单的网站还是复杂的企业级系统,Django 都能提供可靠的支持,帮助开发者快速构建高质量的应用。同时,其活跃的社区和丰富的资源也为开发者在项目实施过程中提供了有力的保障。
159 62

热门文章

最新文章

  • 1
    打造高效的Web Scraper:Python与Selenium的完美结合
    13
  • 2
    Burp Suite Professional 2025.2 (macOS, Linux, Windows) - Web 应用安全、测试和扫描
    26
  • 3
    AppSpider Pro 7.5.015 for Windows - Web 应用程序安全测试
    20
  • 4
    【02】客户端服务端C语言-go语言-web端PHP语言整合内容发布-优雅草网络设备监控系统-2月12日优雅草简化Centos stream8安装zabbix7教程-本搭建教程非docker搭建教程-优雅草solution
    54
  • 5
    部署使用 CHAT-NEXT-WEB 基于 Deepseek
    342
  • 6
    【2025优雅草开源计划进行中01】-针对web前端开发初学者使用-优雅草科技官网-纯静态页面html+css+JavaScript可直接下载使用-开源-首页为优雅草吴银满工程师原创-优雅草卓伊凡发布
    26
  • 7
    java spring 项目若依框架启动失败,启动不了服务提示端口8080占用escription: Web server failed to start. Port 8080 was already in use. Action: Identify and stop the process that’s listening on port 8080 or configure this application to listen on another port-优雅草卓伊凡解决方案
    40
  • 8
    零基础构建开源项目OpenIM桌面应用和pc web- Electron篇
    28
  • 9
    【01】客户端服务端C语言-go语言-web端PHP语言整合内容发布-优雅草网络设备监控系统-硬件设备实时监控系统运营版发布-本产品基于企业级开源项目Zabbix深度二开-分步骤实现预计10篇合集-自营版
    22
  • 10
    FastAPI与Selenium:打造高效的Web数据抓取服务 —— 采集Pixabay中的图片及相关信息
    55