Pagination with Spring MVC, Solr, Thymeleaf and Bootstrap

We're moving Spring Solr onto the page in our NixMash Spring app, so the first thing I wanted to do was demonstrate paging with Spring Solr. Notice the nice Bootstrap pagination piece below? Complete with disabled “next” and “first/last”, highlighted current page and incrementing page elements. Nice! We're going to create it with Spring MVC, a Spring PagedListHolder object and Thymeleaf.

Solr is almost an irrelevant part of the mix, since we're really talking Spring JPA here. We'll start in the Service Implementation class where we see we're returning a List<Product> collection from the Solr Repository.

Since we're dealing with a List<?> (as opposed to a Page<?>) the Spring PlacedListHolder gives us added functionality for setting the current page and navigating through the list. We could also use a Page object and its similar methods, but for this example we'll stick with the PlacedListHolder.

Let's step through the Controller logic.

  1. When we go to /products we redirect to the first page of the Product List. I think this is a cleaner approach than using a Pageable object with “?page=0&size=20&sort=type,desc” query strings. We also want to refresh our Session Product List here if it's present, otherwise the user will return to whatever Product List Page they last visited.
  2. Grab our Session PagedListHolder object.
  3. If it's null we populate it and set the Page Size.
  4. We set the page we want to display based on /products/page/{pageNumber}.
  5. Populate the dimensions used in the Pagination HTML and pass them to the client as Model Attributes.

On The Page

Now we'll create the Bootstrap Pagination control in Thymeleaf, which supplies all of the functionality needed to disable elements, increment page groups and loop through items based on the dimensions we passed from the Controller.

Before I sign off, a huge Hat Tip to Stefan Alexandru who laid all of this out in a 2014 blog post. Stefan used a Page object and has other good commentary on the process if you want to check it out.

Source Code Notes for this Post

All source code discussed in this post can be found in branch v0.2.7 my NixMash Spring GitHub repo and viewed online here.

Posted December 18, 2015 12:38 PM EST

More Like This Post