DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Upgrade Guide To Spring Boot 3.0 for Spring Data JPA and Querydsl
  • Less Code With Spring Data Rest
  • Calling Stored Procedures With IN and OUT Parameters From Spring Data JPA
  • Spring Data: Easy MongoDB Migration Using Mongock

Trending

  • Agentic Systems and Design Patterns
  • AI-Era Cybersecurity, Part 1: Mapping Glasswing, Daybreak, Lightwell and the Tools Racing to Find and Fix Bugs
  • AI Coding Agent Guardrails: Finding Gaps in Tool Permissions
  • When One Docker Swarm Replica Became Unreachable Over an Overlay Network: A Production Case With Traefik

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Data Engineering
  3. Data
  4. Simple Pagination Example With Spring Data and Thymeleaf

Simple Pagination Example With Spring Data and Thymeleaf

Need help with pagination?

By 
Oguzhan Dogan
·
Dec. 19, 18 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
56.6K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

As 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 thePageobject.  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!

Spring Framework Spring Data Data (computing) Thymeleaf

Opinions expressed by DZone contributors are their own.

Related

  • Upgrade Guide To Spring Boot 3.0 for Spring Data JPA and Querydsl
  • Less Code With Spring Data Rest
  • Calling Stored Procedures With IN and OUT Parameters From Spring Data JPA
  • Spring Data: Easy MongoDB Migration Using Mongock

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook