Open In App

Pagination in Spring Webflux

Last Updated : 28 May, 2024
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

The Spring WebFlux is part of Spring Framework and this allows developers to develop non-blocking applications. It provides different operators to handle the publisher and consumers in the application by using Spring reactor. In this article, we explain what is pagination and its uses in web software applications with related examples with output images for understanding the concept in a better way.

In Spring WebFlux, we have Pageable. It is an Abstract interface for pagination information. This interface provides features to develop the pagination in the application. The pagination takes the page number and the number of rows per page. Below we provide a clear spring Application example on this.

Syntax:

Pageable pageable = PageRequest.of(page, size);

Here we use of method from the PageRequest class, this method takes the page number and number of rows per page in the form of input arguments.

Pagination

Pagination is the process of breaking up large data sets into smaller, more manageable pages. This allows users to scroll through the data one page at a time or jump to specific pages. It helps to handle data more efficiently, enhances the user experience by streamlining navigation, and reduces load times by limiting the amount of data captured and displayed at once

Advantages:

  • Improved Performance: Reduces the amount of data fetched and displayed simultaneously, allowing faster loading.
  • Better user experience: Organizing information into smaller, more digestible chunks makes data easier to navigate.
  • Resource Management: Optimizes the use of server and database resources by handling smaller subsets of data.

Example of Pagination in Spring WebFlux

Consider a dataset of 1000 items with a page size of 10. Pagination will divide this dataset into 100 pages, each containing 10 items.

Steps To Implement Pagination in Spring WebFlux

Below is the implementation of Pagination in Spring Webflux.

Project Dependencies:

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb-reactive</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

Project Folder:

After successfully creating the project, the structure will be like below.

Folder Structure
Project Folder


Step 1: Add properties in application.properties

spring.application.name=pagination

spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.database=work


Step 2: Create Entity Class

We have created one Java class named Student.

Student.java:

Java
package com.app;

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@AllArgsConstructor
@NoArgsConstructor
@Data
@Document("student")
public class Student {
    @Id
    private String id;
    private String name;
    private int age;
}


Step 3: Create Page Request Payload

We have created another entity class named PageRequestPayload.

Java
package com.app;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@AllArgsConstructor
@NoArgsConstructor
@Data
public class PageRequestPayload {
    private int page;
    private int size;
}


Step 4: Create Repository

Now, we will create a repository class. The StudentRepository interface extends ReactiveMongoRepository and includes a method for finding students with pagination.

Java
package com.app;

import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.repository.ReactiveMongoRepository;

import reactor.core.publisher.Flux;

public interface StudentRepository extends ReactiveMongoRepository<Student, String> {
    Flux<Student> findAllBy(Pageable pageable);
}


Step 5: Create Controller

Now, we will create a controller class. The StudentController is correctly set up with a POST endpoint to handle pagination requests. The PageRequest.of method creates a pageable object correctly.

Java
package com.app;

import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import reactor.core.publisher.Flux;

@RestController
public class StudentController {

    private final StudentRepository studentRepository;

    public StudentController(StudentRepository studentRepository) {
        this.studentRepository = studentRepository;
    }

    @PostMapping("/students")
    public Flux<Student> getStudents(@RequestBody PageRequestPayload payload) {
        int page = payload.getPage();
        int size = payload.getSize();
        Pageable pageable = PageRequest.of(page, size);
        return studentRepository.findAllBy(pageable);
    }

}


Step 6: Run the Application

Once project development is completed with the required logic, now run this project as Spring Boot App or we can run this project by using Maven commends also. Here run this project as Spring Boot App. This Project runs on an 8080 port number with a Netty server by default.

Application Running


Step 7: Test the APIs

Now test the API endpoint. Here we use the PostMan tool for testing the API endpoint.

Testing with Postman

  • Open Postman and create a new request
  • Now, we need to set the request type to POST and then enter the endpoint URL.
    • http://localhost:8080/students
  • Go to the Body tab and select raw
  • Now provide page and size values in the body
  • Send the request
  • Check the response. You should receive a success message if the file is uploaded successfully.

Case 1:

In this case, the given page is 0 and the size is 3.

http://localhost:8080/students

Output:

students API


Case 2:

In this case, the given page is 1 and the size is 3.

Output:

students API 2



Similar Reads