java
41 lines · 8 steps
How a paginated REST controller works in Spring
A Spring REST controller exposes paginated, filterable product listings and maps entities to clean response DTOs.
Explained by
highlit
1@RestController
2@RequestMapping("/api/products")
3public class ProductController {
4
5 private final ProductRepository productRepository;
6
7 public ProductController(ProductRepository productRepository) {
8 this.productRepository = productRepository;
9 }
10
11 @GetMapping
12 public Page<ProductResponse> listProducts(
13 @RequestParam(required = false) String category,
14 @PageableDefault(size = 20, sort = "createdAt", direction = Sort.Direction.DESC)
15 Pageable pageable) {
16
17 Page<Product> products = (category == null || category.isBlank())
18 ? productRepository.findAll(pageable)
19 : productRepository.findByCategoryIgnoreCase(category, pageable);
20
21 return products.map(ProductResponse::from);
22 }
23
24 @GetMapping("/{id}")
25 public ResponseEntity<ProductResponse> getProduct(@PathVariable Long id) {
26 return productRepository.findById(id)
27 .map(ProductResponse::from)
28 .map(ResponseEntity::ok)
29 .orElseGet(() -> ResponseEntity.notFound().build());
30 }
31
32 public record ProductResponse(Long id, String name, String category, BigDecimal price) {
33 static ProductResponse from(Product product) {
34 return new ProductResponse(
35 product.getId(),
36 product.getName(),
37 product.getCategory(),
38 product.getPrice());
39 }
40 }
41}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Mapping entities to dedicated response records keeps your API contract decoupled from your persistence model.
- 2Spring's Pageable and @PageableDefault hand you paging and sorting from query parameters with almost no code.
- 3Returning ResponseEntity lets a single handler express both success and 404 outcomes cleanly.
Related explainers
python
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException, status from pydantic import BaseModel, EmailStr from sqlalchemy.orm import Session
Building a signup endpoint in FastAPI
dependency-injection
request-validation
background-tasks
Intermediate
8 steps
java
public interface GitHubClient { @GetExchange("/users/{username}") GitHubUser getUser(@PathVariable String username);
Declarative HTTP clients in Spring
http-client
declarative-api
proxy
Intermediate
8 steps
java
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map;
Building a trie for autocomplete in Java
trie
prefix-tree
recursion
Intermediate
8 steps
php
<?php namespace App\Providers;
Subdomain multi-tenancy routing in Laravel
multi-tenancy
service-container
route-binding
Advanced
7 steps
ruby
module Paginatable extend ActiveSupport::Concern private
A reusable pagination concern in Rails
pagination
concerns
http-headers
Intermediate
8 steps
java
@RestController @RequestMapping("/api/products") public class ProductSearchController {
Binding collection query params in Spring
rest-api
query-parameters
dependency-injection
Intermediate
6 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/how-a-paginated-rest-controller-works-in-spring-explained-java-2496/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.