How to implement pagination in Spring MVC 3 [closed] How to implement pagination in Spring MVC 3 [closed] spring spring

How to implement pagination in Spring MVC 3 [closed]


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);    }}


I was looking for a way to do that, too, but didn't find any standard component or taglib. I think mainly because paging can become very specific since you need to retrieve your data with paging from the database already (if you are using Hibernate you can easily do that using the Criteria API). I came up with something like this:

public class Pager{    private int page;    private int results;    private String sortOrder;    private String sortColumn;    // Getters and setters}@Controllerpublic 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));    }}

If you now perform a request to http://domain/app/test.html?id=10&page=1&results=30&sortOrder=asc you will get the pager Object in your request.


Have you ever heard about the Spring Data JPA project? There is a nice flexible solution using the Pagable interface. I've found it to be the simplest way to achieve clean, boilerplate-free pagination. Check out more at the Spring Data JPA homepage.