Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
Spring MVC - Pagination with Example
Next article icon

Spring MVC - Pagination with Example

Last Updated : 12 May, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

We will be explaining how we can implement pagination in Spring MVC Application. This is required when we need to show a lot of data on pages. Suppose in an e-commerce site we have a lot of products but we can't show all of those on a single page, so we will show only 20 products on each page. This will help in better product tracking and a great user experience. Paging can be implemented using 2 ways:

  1. From scratch - This is done by querying the database using the offset and the pageSize. This is only used if we need to customize paging more than pageSize and offset.
  2. Using precompiled repositories - This is done by extending Repositories that have implemented pagination using scratch. This is more generally used.

We will be using the second method by extending from the PagingAndSortingRepository interface for example, but we can use JpaRepository also for the same. These interfaces have the implementations to do paging and sorting.

package org.springframework.data.repository;    import org.springframework.data.domain.Page;  import org.springframework.data.domain.Pageable;  import org.springframework.data.domain.Sort;    @NoRepositoryBean  public interface PagingAndSortingRepository<T, ID> extends CrudRepository<T, ID> {     Iterable<T> findAll(Sort sort);     Page<T> findAll(Pageable pageable);  }

We will get the page from these functions by passing the Pageable instance.

Steps to Implement Pagination

Setup the database and create an entity. 

Java
package com.geeksforgeeks.Spring.MVC.Pagination.data;  import lombok.Data; import javax.persistence.*;  @Entity @Table @Data public class Product {      @Id     @Column(name = "id")     @GeneratedValue(strategy = GenerationType.IDENTITY)     private int id;      @Column(name = "price")     private int price;      @Column(name = "name")     private String name;  } 

Create a Repository interface extending PagingAndSortingRepository.

Java
package com.geeksforgeeks.Spring.MVC.Pagination.repositories;  import com.geeksforgeeks.Spring.MVC.Pagination.data.Product; import org.springframework.data.repository.PagingAndSortingRepository; import org.springframework.stereotype.Repository;  // we can also extend from JpaRepository here  @Repository public interface ProductRepository extends PagingAndSortingRepository<Product,Integer> {  } 

Create a service that will perform operations on the data retrieved from the repository. Here we will pass the pageable instance in the findAll function and that will return a page. 

Java
package com.geeksforgeeks.Spring.MVC.Pagination.services;  import com.geeksforgeeks.Spring.MVC.Pagination.data.Product; import com.geeksforgeeks.Spring.MVC.Pagination.repositories.ProductRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.PageRequest; import org.springframework.stereotype.Service;  import java.util.List;  @Service public class ProductService {      @Autowired     private ProductRepository productRepository;      public void saveAllProducts(List<Product>products){         productRepository.saveAll(products);     }      public Iterable<Product> getAllProducts(Integer pageSize,Integer offset) {         return productRepository.findAll(PageRequest.of(offset,pageSize));     } } 

Create a rest api that will show the data in the pages. Here we will receive the page and give the response to the user 

Java
package com.geeksforgeeks.Spring.MVC.Pagination.controllers;  import com.geeksforgeeks.Spring.MVC.Pagination.data.Product; import com.geeksforgeeks.Spring.MVC.Pagination.services.ProductService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*;  import javax.annotation.PostConstruct; import javax.websocket.server.PathParam; import java.util.ArrayList; import java.util.List;  @RestController @RequestMapping public class ProductController {      @Autowired     private ProductService productService;      @PostConstruct     public void createProducts(){         List<Product>products = new ArrayList<>();         for(int i=0;i<100;i++){             Product product = new Product();             product.setPrice(i);             product.setName("product+"+ i);             products.add(product);         }         productService.saveAllProducts(products);     }      @GetMapping("/getAll/{offset}")     public Iterable<Product> getAllProducts(@RequestParam Integer pageSize, @PathVariable("offset") Integer offset){         return productService.getAllProducts(pageSize,offset);     } } 

Output: 

The JSON Response from the backend will look like this

Output
 

This response is then converted to the frontend according to in web, android, or ios.


Next Article
Spring MVC - Pagination with Example

B

bhavyajain4641
Improve
Article Tags :
  • Java
Practice Tags :
  • Java

Similar Reads

    Spring MVC - Get Probability of a Gender by Providing a Name using REST API
    A lot of funful REST API calls are available as open source. Suppose if we like to keep a name to our nears and dears, we can just check that by means of a REST API call and get the gender, what is the probability of being that gender and how many times does it come with it? Relevant REST API call h
    7 min read
    Get Time Zone by Providing Latitude and Longitude using Spring MVC and REST API
    Spring MVC Framework follows the Model-View-Controller design pattern. It is used to develop web applications. It works around DispatcherServlet. DispatcherServlet handles all the HTTP requests and responses. In this article, we are going to see about a REST API call to find the coordinates for the
    6 min read
    Spring MVC with MySQL and Junit - Finding Employees Based on Location
    In real-world scenarios, organizations are existing in different localities. Employees are available in many locations. Sometimes they work in different 2 locations i.e. for a few days, they work on location 1 and for a few other days, they work on location 2. Let's simulate this scenario via MySQL
    8 min read
    Spring MVC - Get University/College Details via REST API
    REpresentational State Transfer (REST) is an architectural style that defines a set of constraints to be used for creating web services. REST API is a way of accessing web services in a simple and flexible way without having any processing. Spring MVC is a Web MVC Framework for building web applicat
    6 min read
    Spring MVC - JSTL forEach Tag with Example
    JSP Standard Tag Library (JSTL) is a set of tags that can be used for implementing some common operations such as looping, conditional formatting, and others. JSTL aims to provide an easy way to maintain SP pages The use of tags defined in JSTL has Simplified the task of the designers to create Web
    6 min read
    Spring MVC - Iterating List on JSP using JSTL
    JSP Standard Tag Library (JSTL) is a set of tags that can be used for implementing some common operations such as looping, conditional formatting, and others. JSTL aims to provide an easy way to maintain SP pages The use of tags defined in JSTL has Simplified the task of the designers to create Web
    6 min read
    Two-Way Data Binding in Spring MVC with Example
    Data Binding, as the name itself, is a self-explanatory word. In data binding what we have to do is we have to capture or store the data so that we can bind that data with another resource (for example displaying the data in the frontend part) as per our needs or we can also read the data from a var
    7 min read
    Spring MVC - Basic Example using JSTL
    JSP Standard Tag Library (JSTL) is a set of tags that can be used for implementing some common operations such as looping, conditional formatting, and others. JSTL aims to provide an easy way to maintain SP pages The use of tags defined in JSTL has Simplified the task of the designers to create Web
    8 min read
    Spring MVC @ModelAttribute Annotation with Example
    In Spring MVC, the @ModelAttribute annotation binds a method parameter or method return value to a named model attribute and then exposes it to a web view. It refers to the property of the Model object. For example, if we have a form with a form backing object that is called "Student" then we can ha
    8 min read
    Data Transfer Object (DTO) in Spring MVC with Example
    In Spring Framework, Data Transfer Object (DTO) is an object that carries data between processes. When you're working with a remote interface, each call is expensive. As a result, you need to reduce the number of calls. The solution is to create a Data Transfer Object that can hold all the data for
    7 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences