Spring MVC - Pagination with Example
Last Updated :
12 May, 2022
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:
- 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.
- 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
This response is then converted to the frontend according to in web, android, or ios.
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