如何在春季 MVC 3 中实现分页 [已关闭]

2022-08-31 17:30:44

是否有任何开箱即用、易于实现的标准分页组件/标签库或代码示例可用于 Spring MVC 中的分页?


答案 1

看看 PagedListHolderorg.springframework.beans.support 中的其他类。

有关一些示例,请参阅示例中的 JPetstore,例如在 SearchProductsController 中.java

public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
    String keyword = request.getParameter("keyword");
    if (keyword != null) {
        if (!StringUtils.hasLength(keyword)) {
            return new ModelAndView("Error", "message", "Please enter a keyword to search for, then press the search button.");
        }
        PagedListHolder productList = new PagedListHolder(this.petStore.searchProductList(keyword.toLowerCase()));
        productList.setPageSize(4);
        request.getSession().setAttribute("SearchProductsController_productList", productList);
        return new ModelAndView("SearchProducts", "productList", productList);
    }
    else {
        String page = request.getParameter("page");
        PagedListHolder productList = (PagedListHolder) request.getSession().getAttribute("SearchProductsController_productList");
        if (productList == null) {
            return new ModelAndView("Error", "message", "Your session has timed out. Please start over again.");
        }
        if ("next".equals(page)) {
            productList.nextPage();
        }
        else if ("previous".equals(page)) {
            productList.previousPage();
        }
        return new ModelAndView("SearchProducts", "productList", productList);
    }
}

答案 2

我也在寻找一种方法来做到这一点,但没有找到任何标准组件或taglib。我认为主要是因为分页可以变得非常具体,因为您需要从数据库中通过分页来检索数据(如果您使用的是Hibernate,则可以使用标准API轻松执行此操作)。我想出了这样的东西:

public class Pager
{
    private int page;
    private int results;
    private String sortOrder;
    private String sortColumn;

    // Getters and setters
}

@Controller
public class StuffController
{
    @Autowired SomeEntityService someEntityService;

    @RequestMapping("/test.html", method = Method.GET)
    public void getStuffPaged(@RequestParam("id") String id, Pager pager, ModelMap mm)
    {
        mm.addAttribute("entities", someEntityService.get(id, pager));
    }
}

如果您现在执行请求,您将在请求中获得寻呼机对象。http://domain/app/test.html?id=10&page=1&results=30&sortOrder=asc