Simple Pagination Example With Spring Data and Thymeleaf
Need help with pagination?
Join the DZone community and get the full member experience.
Join For FreeAs some of you know, pagination is used to display big result sets. Sometimes, it's hard to list all the data at once. In these cases, pagination techniques are used to divide and display the big result set. In this tutorial, I'll try to show you a simple pagination example with Spring Boot, Spring Data, and Thymeleaf.
For this tutorial, I use a sample Article CRUD web application, which I designed previously.
First of all, I chose Spring Boot 2.0.5.RELEASE, MySQL, Spring Data, and Thymeleaf for the Article CRUD application.
So before starting, you need to have these dependencies, aside from the usual Spring Boot dependencies.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
A POJO is created for the Article
entity, as shown below:
@Entity
@Table(name = "article")
public class Article {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private long id;
@Column(name = "url")
private String url;
@Column(name = "status")
private String status;
//getters and setters
}
A DAO interface, which extends from the CrudRepository, is created. This is what makes difference.
public interface ArticleDao extends CrudRepository<Article, Long> {
Page<Article> findAll(Pageable pageable);
}
For listing articles with pagination, a Controller
method is created:
@RequestMapping(value = "/article-list/page/{page}")
public ModelAndView listArticlesPageByPage(@PathVariable("page") int page) {
ModelAndView modelAndView = new ModelAndView("article-list-paging");
PageRequest pageable = PageRequest.of(page - 1, 15);
Page<Article> articlePage = articleService.getPaginatedArticles(pageable);
int totalPages = articlePage.getTotalPages();
if(totalPages > 0) {
List<Integer> pageNumbers = IntStream.rangeClosed(1,totalPages).boxed().collect(Collectors.toList());
modelAndView.addObject("pageNumbers", pageNumbers);
}
modelAndView.addObject("activeArticleList", true);
modelAndView.addObject("articleList", articlePage.getContent());
return modelAndView;
}
You can see that the Spring Data PageRequest
object (org.springframework.data.domain.PageRequest) is used in the controller. I preferred to pass page size as static but I strongly recommend you read it from the properties file. I passed this PageRequest
object to a method in theArticleService
. Let's see what is inside this service method.
@Service
public class ArticleServiceImpl implements ArticleService {
@Autowired
private ArticleDao articleDao;
@Override
public Page<Article> getPaginatedArticles(Pageable pageable) {
return articleDao.findAll(pageable);
}
}
In thegetPaginatedArticles
method, the findAll(Pageable pageable)
method in ArticleDao
is called. ArticleDao
's findAll
method returns the records sorted by ID using page and page size, which we provided in thePageRequest
object.
In the end, we have the Page<Article>
object in the controller. We retrieve the list of Article by calling the getContent()
method of thePage
object. And below, you can see how the article list is displayed and how pagination is done with the help of Thymeleaf.
<div class="row" th:fragment="article-list" th:if="${articleList != null && !articleList.isEmpty()}">
<div class="col-md-2"></div>
<div class="col-md-8">
<table id="link-list" class="table table-striped table-bordered" style="width:100%">
<thead>
<tr>
<th>ID</th>
<th>URL</th>
<th>Status</th>
<th>Detail</th>
</tr>
</thead>
<tbody>
<tr th:each="article : ${articleList}">
<td th:text="${{article.id}}">1</td>
<td th:text="${{article.url}}">http://thegame.org</td>
<td th:text="${{article.status}}">PENDING</td>
<td><a th:href="@{/article/detail/{articleId}(articleId=${article.id})}">Detail</a></td>
</tr>
</tbody>
</table>
</div>
<div class="col-md-2"></div>
</div>
<div class="row" th:fragment="pagination">
<div class="col-md-2"></div>
<div class="col-md-8">
<nav aria-label="Pagination">
<ul class="pagination justify-content-center">
<li class="page-item" th:each="pageNumber : ${pageNumbers}" >
<a class="page-link" th:href="@{|/article-list/page/${pageNumber}|}" th:text=${pageNumber}>1</a>
</li>
</ul>
</nav>
</div>
<div class="col-md-2"></div>
</div>
That's all!
Conclusion
Now, we have a sample pagination example. I know that there are some unhandled errors in it, but it's up to you to use and improve upon this example. There're lots of techniques and methods for pagination. I only wanted to give an example today
Happy coding!
Opinions expressed by DZone contributors are their own.
Comments