Is there any out-of-the-box, easy to implement, standard pagination component/tag-lib or code-sample available for pagination in Spring MVC?
Once we have our repository extending from PagingAndSortingRepository, we just need to: Create or obtain a PageRequest object, which is an implementation of the Pageable interface. Pass the PageRequest object as an argument to the repository method we intend to use.
Pagination is used to display a large number of records in different parts. In such case, we display 10, 20 or 50 records in one page. For remaining records, we provide links. We can simply create pagination example in Spring MVC.
The simplest way to implement pagination is to use the Java Query Language – create a query and configure it via setMaxResults and setFirstResult: Query query = entityManager. createQuery("From Foo"); int pageNumber = 1; int pageSize = 10; query.
It provides two methods : Page findAll(Pageable pageable) – returns a Page of entities meeting the paging restriction provided in the Pageable object. Iterable findAll(Sort sort) – returns all entities sorted by the given options. No paging is applied here.
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); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With