PagingAndSortingRepository – How to Use With Thymeleaf

For this tutorial, I will demonstrate how to display a list of a business’ clients in Thymeleaf with pagination.

View and Download the code from Github

1 – Project Structure

We have a normal Maven project structure.
Maven structure of PagingAndSortingRepository Example

2 – Project Dependencies

Besides the normal Spring dependencies, we add Thymeleaf and hsqldb because we are using an embedded database.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="" xmlns:xsi=""


	<description>Michael C  Good - PagingAndSortingRepository</description>

		<relativePath /> <!-- lookup parent from repository -->






3 – Models

We define the following fields for a client:

  • a unique identifier
  • name of the client
  • an address of the client
  • the amount owed on the current invoice

The getters and setters are quickly generated in Spring Tool Suite.
The @Entity annotation is needed for registering this model to @SpringBootApplication.

package com.michaelcgood.model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

public class ClientModel {
	@GeneratedValue(strategy = GenerationType.AUTO)
	private Long id;
	public Long getId() {
		return id;
	public void setId(Long id) { = id;
	public String getName() {
		return name;
	public void setName(String name) { = name;
	public String getAddress() {
		return address;
	public void setAddress(String address) {
		this.address = address;
	public Integer getCurrentInvoice() {
		return currentInvoice;
	public void setCurrentInvoice(Integer currentInvoice) {
		this.currentInvoice = currentInvoice;
	private String name;
	private String address;
	private Integer currentInvoice;


The PagerModel is just a POJO (Plain Old Java Object), unlike the ClientModel. There are no imports, hence no annotations. This PagerModel is purely just used for helping with the pagination on our webpage. Revisit this model once you read the Thymeleaf template and see the demo pictures. The PagerModel makes more sense when you think about it in context.

package com.michaelcgood.model;

public class PagerModel {
	private int buttonsToShow = 5;

	private int startPage;

	private int endPage;

	public PagerModel(int totalPages, int currentPage, int buttonsToShow) {


		int halfPagesToShow = getButtonsToShow() / 2;

		if (totalPages <= getButtonsToShow()) {

		} else if (currentPage - halfPagesToShow <= 0) {

		} else if (currentPage + halfPagesToShow == totalPages) {
			setStartPage(currentPage - halfPagesToShow);

		} else if (currentPage + halfPagesToShow > totalPages) {
			setStartPage(totalPages - getButtonsToShow() + 1);

		} else {
			setStartPage(currentPage - halfPagesToShow);
			setEndPage(currentPage + halfPagesToShow);


	public int getButtonsToShow() {
		return buttonsToShow;

	public void setButtonsToShow(int buttonsToShow) {
		if (buttonsToShow % 2 != 0) {
			this.buttonsToShow = buttonsToShow;
		} else {
			throw new IllegalArgumentException("Must be an odd value!");

	public int getStartPage() {
		return startPage;

	public void setStartPage(int startPage) {
		this.startPage = startPage;

	public int getEndPage() {
		return endPage;

	public void setEndPage(int endPage) {
		this.endPage = endPage;

	public String toString() {
		return "Pager [startPage=" + startPage + ", endPage=" + endPage + "]";


4 – Repository

The PagingAndSortingRepository is an extension of the CrudRepository. The only difference is that it allows you to do pagination of entities. Notice that we annotate the interface with @Repository to make it visible to @SpringBootApplication.

package com.michaelcgood.dao;

import org.springframework.stereotype.Repository;

import com.michaelcgood.model.ClientModel;

public interface ClientRepository extends PagingAndSortingRepository<ClientModel,Long> {


5 – Controller

We define some variables in the beginning of the class. We only want to show 3 page buttons at time. The initial page is the first page of results, the initial amount of items on the page is 5, and the user has the ability to have either 5 or 10 results per page.

We add some example values to our repository with the addtorepository() method, which is defined further below in this class. With the addtorepository method(), we add several “clients” to our repository, and many of them are hat companies because I ran out of ideas.

ModelAndView is used here rather than Model. ModelAndView is used instead because it is a container for both a ModelMap and a view object. It allows the controller to return both as a single value. This is desired for what we are doing.

package com.michaelcgood.controller;

import java.util.Optional;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import com.michaelcgood.model.PagerModel;
import org.springframework.beans.factory.annotation.Autowired;

import com.michaelcgood.dao.ClientRepository;
import com.michaelcgood.model.ClientModel;

public class ClientController {
	private static final int BUTTONS_TO_SHOW = 3;
	private static final int INITIAL_PAGE = 0;
	private static final int INITIAL_PAGE_SIZE = 5;
	private static final int[] PAGE_SIZES = { 5, 10};
	ClientRepository clientrepository;
	public ModelAndView homepage(@RequestParam("pageSize") Optional<Integer> pageSize,
			@RequestParam("page") Optional<Integer> page){
		ModelAndView modelAndView = new ModelAndView("index");
		// Evaluate page size. If requested parameter is null, return initial
		// page size
		int evalPageSize = pageSize.orElse(INITIAL_PAGE_SIZE);
		// Evaluate page. If requested parameter is null or less than 0 (to
		// prevent exception), return initial size. Otherwise, return value of
		// param. decreased by 1.
		int evalPage = (page.orElse(0) < 1) ? INITIAL_PAGE : page.get() - 1;
		// print repo
		System.out.println("here is client repo " + clientrepository.findAll());
		Page<ClientModel> clientlist = clientrepository.findAll(new PageRequest(evalPage, evalPageSize));
		System.out.println("client list get total pages" + clientlist.getTotalPages() + "client list get number " + clientlist.getNumber());
		PagerModel pager = new PagerModel(clientlist.getTotalPages(),clientlist.getNumber(),BUTTONS_TO_SHOW);
		// add clientmodel
		// evaluate page size
		modelAndView.addObject("selectedPageSize", evalPageSize);
		// add page sizes
		modelAndView.addObject("pageSizes", PAGE_SIZES);
		// add pager
		modelAndView.addObject("pager", pager);
		return modelAndView;
public void addtorepository(){
		//below we are adding clients to our repository for the sake of this example
				ClientModel widget = new ClientModel();
				widget.setAddress("123 Fake Street");
				widget.setName("Widget Inc");;
				//next client
				ClientModel foo = new ClientModel();
				foo.setAddress("456 Attorney Drive");
				foo.setName("Foo LLP");;
				//next client
				ClientModel bar = new ClientModel();
				bar.setAddress("111 Bar Street");
				bar.setName("Bar and Food");;
				//next client
				ClientModel dog = new ClientModel();
				dog.setAddress("222 Dog Drive");
				dog.setName("Dog Food and Accessories");;
				//next client
				ClientModel cat = new ClientModel();
				cat.setAddress("333 Cat Court");
				cat.setName("Cat Food");;
				//next client
				ClientModel hat = new ClientModel();
				hat.setAddress("444 Hat Drive");
				hat.setName("The Hat Shop");;
				//next client
				ClientModel hatB = new ClientModel();
				hatB.setAddress("445 Hat Drive");
				hatB.setName("The Hat Shop B");;
				//next client
				ClientModel hatC = new ClientModel();
				hatC.setAddress("446 Hat Drive");
				hatC.setName("The Hat Shop C");;
				//next client
				ClientModel hatD = new ClientModel();
				hatD.setAddress("446 Hat Drive");
				hatD.setName("The Hat Shop D");;
				//next client
				ClientModel hatE = new ClientModel();
				hatE.setAddress("447 Hat Drive");
				hatE.setName("The Hat Shop E");;
				//next client
				ClientModel hatF = new ClientModel();
				hatF.setAddress("448 Hat Drive");
				hatF.setName("The Hat Shop F");;

6 – Thymeleaf Template

In Thymeleaf template, the two most important things to note are:

  • Thymeleaf Standard Dialect
  • Javascript

Like in a CrudRepository, we iterate through the PagingAndSortingRepository with th:each=”clientlist : ${clientlist}”. Except instead of each item in the repository being an Iterable, the item is a Page.

With select class=”form-control pagination” id=”pageSizeSelect”, we are allowing the user to pick their page size of either 5 or 10. We defined these values in our Controller.

Next is the code that allows the user to browse the various pages. This is where our PagerModel comes in to use.

The changePageAndSize() function is the JavaScript function that will update the page size when the user changes it.

<html xmlns=""

<!-- CSS INCLUDE -->
<link rel="stylesheet"

.pagination-centered {
	text-align: center;

.disabled {
	pointer-events: none;
	opacity: 0.5;

.pointer-disabled {
	pointer-events: none;


	<div class="container-fluid">
		<!-- commented out     <div th:replace="fragments/header :: header">&nbsp;</div> -->
		<!-- PAGE TITLE -->
		<div class="page-title">
				<span class="fa fa-arrow-circle-o-left"></span> Client Viewer
		<!-- END PAGE TITLE -->
		<div class="row">
			<table class="table datatable">
					<tr th:each="clientlist : ${clientlist}">
						<td th:text="${}">Text ...</td>
						<td th:text="${clientlist.address}">Text ...</td>
						<td><button type="button"
								class="btn btn-primary btn-condensed">
								<i class="glyphicon glyphicon-folder-open"></i>
			<div class="row">
				<div class="form-group col-md-1">
					<select class="form-control pagination" id="pageSizeSelect">
						<option th:each="pageSize : ${pageSizes}" th:text="${pageSize}"
							th:selected="${pageSize} == ${selectedPageSize}"></option>
				<div th:if="${clientlist.totalPages != 1}"
					class="form-group col-md-11 pagination-centered">
					<ul class="pagination">
						<li th:class="${clientlist.number == 0} ? disabled"><a
							th:href="@{/(pageSize=${selectedPageSize}, page=1)}">&laquo;</a>
						<li th:class="${clientlist.number == 0} ? disabled"><a
							th:href="@{/(pageSize=${selectedPageSize}, page=${clientlist.number})}">&larr;</a>
							th:class="${clientlist.number == (page - 1)} ? 'active pointer-disabled'"
							th:each="page : ${#numbers.sequence(pager.startPage, pager.endPage)}">
							<a class="pageLink"
							th:href="@{/(pageSize=${selectedPageSize}, page=${page})}"
							th:class="${clientlist.number + 1 == clientlist.totalPages} ? disabled">
							<a class="pageLink"
							th:href="@{/(pageSize=${selectedPageSize}, page=${clientlist.number + 2})}">&rarr;</a>
							th:class="${clientlist.number + 1 == clientlist.totalPages} ? disabled">
							<a class="pageLink"
							th:href="@{/(pageSize=${selectedPageSize}, page=${clientlist.totalPages})}">&raquo;</a>

	<script th:inline="javascript">
		$(document).ready(function() {

function changePageAndSize() {
	$('#pageSizeSelect').change(function(evt) {
		window.location.replace("/?pageSize=" + this.value + "&page=1");


7 – Configuration

The below properties can be changed based on your preferences but were what I wanted for my environment.

# = Thymeleaf configurations 

8 – Demo

This is the homepage.

Homepage PartingAndSortingRepository Example

This is the second page.
Second Page PagingAndSortingRepository

I can change the amount of items on the page to 10.
Change page size to 10 PagingAndSortingRepository

The source code is on Github

Published by Michael

I started my website in 2017 to help people learn more about information technology in order to help them become more successful in their careers. I earned my bachelor's degree from New York University, have been working in cyber security since 2012, and live in the Washington D.C. Metro area. I have found running a blog to be one of the greatest assets in helping my career and have found it could even bring in a few extra bucks each month. Starting a blog is easy and rewarding. To keep my knowledge current, I take courses on Udemy and Treehouse. By using my links, you can get a discount on both.

Join the Conversation


  1. Hi Michael,
    The posting is simply awesome and working perfectly in my Eclipse.
    I do want to implement the same in my project, where I implemented Spring Security.
    In my project, it’s redirecting to login page after clicking on ‘page 2’ button. (Your pagination integrated)
    Initial page with pagination buttons is coming perfectly, but after clicking on 2 or 3 button, redirecting to login page.
    I’m unable to configure the same in my configure(HttpSecurity http) method of Spring Security.
    Request you to hint me to how to configure this.

    Thanks in advance
    Srini. P.

Leave a comment

Your email address will not be published. Required fields are marked *

%d bloggers like this: