【问题标题】:Pagination of a List of objects in SpringSpring中对象列表的分页
【发布时间】:2021-07-18 02:00:13
【问题描述】:

我的控制器中有一个对象列表

    public String postResults(Model model, @RequestParam String shopName) throws IOException {
        DataFilter filter = new DataFilter();
        List<Row> rows = filter.filterRows(shopName);
        model.addAttribute("results", rows);
        return "results";
    }   

以及下面的部分模板:

           <tr th:each="obj : ${results}">
               <td><img th:src="${obj.image}" th:class="images"></td>
               <td th:utext="${obj.description}"></td>
               <td th:utext="${obj.price}"></td>
           </tr>

目前我正在尝试弄清楚如何在这里实现分页。

附:我已经在基于存储库的同一个项目中进行了分页,现在我需要在没有它的情况下实现相同的分页,只需使用对象列表

【问题讨论】:

  • 仅使用List of objects 分页是不可能的。您需要使用一些唯一 ID 将列表临时保存在内存(或存储)中,并且这些唯一 ID 应与每个请求一起传递以获取数据(以及页码)。但这不是可扩展的解决方案。数据库分页是您应该使用的。
  • 你的意思是这样? List&lt;Row&gt; rows = filter.filterRows(shopName); Pageable pageable = PageRequest.of(0, 25); Page&lt;Row&gt; page = new PageImpl&lt;&gt;(rows, pageable, rows.size());

标签: java spring pagination


【解决方案1】:

感谢 cmets。在数据库帮助下做到了这一点。在数据库中保存对象列表,然后从数据库中选择它并分页:

@GetMapping("/results")
    public String getResults(HttpServletRequest request, Model model) {
        int page = 0;
        int size = 10;

        if (request.getParameter("page") != null && !request.getParameter("page").isEmpty()) {
            page = Integer.parseInt(request.getParameter("page")) - 1;
        }

        if (request.getParameter("size") != null && !request.getParameter("size").isEmpty()) {
            size = Integer.parseInt(request.getParameter("size"));
        }

        model.addAttribute("results", resultRepository.findAll(PageRequest.of(page, size)));
        return "results";
    }

    @PostMapping("/results")
    public String postResults(Model model, @RequestParam String shopName) throws IOException {
        DataFilter filter = new DataFilter();
        List<Row> rows = filter.filterRows(shopName);
        resultRepository.deleteAll();
        resultRepository.saveAll(rows);
        return "redirect:/results";
    }

【讨论】:

    猜你喜欢
    • 2021-01-23
    • 1970-01-01
    • 1970-01-01
    • 2019-05-10
    • 1970-01-01
    • 1970-01-01
    • 2015-05-30
    • 2011-02-02
    • 1970-01-01
    相关资源
    最近更新 更多