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
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
Building Scalable Real-Time Apps with AstraDB and Vaadin
Register Now

Trending

  • The Role of AI and Programming in the Gaming Industry: A Look Beyond the Tables
  • Top Six React Development Tools
  • Writing a Vector Database in a Week in Rust
  • Send Email Using Spring Boot (SMTP Integration)

Trending

  • The Role of AI and Programming in the Gaming Industry: A Look Beyond the Tables
  • Top Six React Development Tools
  • Writing a Vector Database in a Week in Rust
  • Send Email Using Spring Boot (SMTP Integration)
  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?

Oguzhan Dogan user avatar by
Oguzhan Dogan
·
Dec. 19, 18 · Tutorial
Like (3)
Save
Tweet
Share
53.95K Views

Join the DZone community and get the full member experience.

Join For Free

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.

Trending

  • The Role of AI and Programming in the Gaming Industry: A Look Beyond the Tables
  • Top Six React Development Tools
  • Writing a Vector Database in a Week in Rust
  • Send Email Using Spring Boot (SMTP Integration)

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com

Let's be friends: