Spring Boot项目如何将Model中的商品列表返回至HTML页面展示
实现商品列表在页面展示的操作步骤
1. 基础配置校验
- 首先确认你的Spring项目已引入Thymeleaf模板引擎依赖(Spring Boot项目推荐使用该模板解析Model中的数据),Maven项目在
pom.xml中添加如下依赖:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
- 你的控制器方法返回的视图名为
itemView,因此需要将你的页面文件命名为itemView.html,放置在项目的src/main/resources/templates目录下,若你坚持使用item.html需要修改控制器返回值为item,否则会出现视图找不到的错误。
2. 改造HTML模板渲染列表
你需要在HTML中引入Thymeleaf的命名空间,使用Thymeleaf的遍历语法渲染listofitems中的商品数据,改造后的完整HTML代码如下:
<!DOCTYPE html> <!-- 引入Thymeleaf命名空间 --> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>List of Items</title> </head> <body> <form method="post" action="api/item/listItems"> <h1>Search Items</h1> <div class="inset"> <p> <label for="itemCode">Item Code</label> <input type="text" name="itemCode" id="itemCode"> </p> <p> <label for="itemEnum">Active / No Active</label> <input type="text" name="itemEnum" id="itemEnum"> </p> <p> <label for="MaxPrice">Max Price</label> <input type="text" name="MaxPrice" id="MaxPrice"> </p> <p> <!-- 修正原有笔误,MinPrice的label写错为Max Price --> <label for="MinPrice">Min Price</label> <input type="text" name="MinPrice" id="MinPrice"> </p> <p> If you don´t complete a filter, that filter won´t be taken into account. </p> </div> <p class="p-container"> <input name="submit" type="submit" value="See Items" /> </p> </form> <h2>商品列表</h2> <!-- 列表非空时展示表格 --> <table border="1" th:if="${not #lists.isEmpty(listofitems)}"> <tr> <th>商品编码</th> <th>商品价格</th> <th>商品状态</th> </tr> <tr th:each="item : ${listofitems}"> <td th:text="${item.itemCode}"></td> <td th:text="${item.price}"></td> <td th:text="${item.itemEnum.estado}"></td> </tr> </table> <!-- 列表为空时展示提示 --> <p th:if="${#lists.isEmpty(listofitems)}">暂无符合条件的商品</p> </body> </html>
上述代码中th:each会自动遍历你传入的listofitems列表,逐行渲染商品数据,你可以根据你的Item类的实际属性调整展示的字段。
可选优化建议
你现有控制器的@RequestParam默认是必填项,若用户提交表单时未填写对应参数会直接报错,建议修改参数配置如下:
@PostMapping("/listItems") public String listItems( @RequestParam(value = "itemCode", required = false, defaultValue = "") String itemCode, @RequestParam(value = "MaxPrice", required = false, defaultValue = "1000000") Integer MaxPrice, @RequestParam(value = "MinPrice", required = false, defaultValue = "0") Integer MinPrice, @RequestParam(value = "itemEnum", required = false, defaultValue = "") String itemEnum, @ModelAttribute("item") Item item, ModelMap model ){ List<Item> itemList = itemRepository.findAll(); List<Item> finalItemList = new ArrayList<>(); for(Item i : itemList){ if(i.getPrice() <= MaxPrice && i.getPrice() >= MinPrice){ if(itemCode.isEmpty() || i.getItemCode().equals(itemCode)){ if(itemEnum.isEmpty() || i.getItemEnum().getEstado().equals(itemEnum)){ finalItemList.add(i); } } } } model.addAttribute("listofitems", finalItemList); return "itemView"; }
将基本类型int改为包装类Integer,同时设置required = false和默认值,避免空参数报错。
内容的提问来源于stack exchange,提问作者Jesús Navarro Hernández
相关产品推荐
相关产品推荐

