How to implement pagination in Spring MVC 3

Nachiket picture Nachiket · Feb 11, 2010 · Viewed 80.5k times · Source

Is there any out-of-the-box, easy to implement, standard pagination component/tag-lib or code-sample available for pagination in Spring MVC?

Answer

Pascal Thivent picture Pascal Thivent · Feb 11, 2010

Have a look at PagedListHolder and other classes from org.springframework.beans.support.

See the JPetstore in the samples for some examples, e.g. in 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);
    }
}