java 51 lines · 7 steps

Binding paged search filters in Spring

A Spring REST endpoint binds query parameters into a validated criteria object and returns a paginated result.

Explained by highlit
1@RestController
2@RequestMapping("/api/products")
3@RequiredArgsConstructor
4public class ProductSearchController {
5 
6 private final ProductQueryService productQueryService;
7 
8 @GetMapping("/search")
9 public Page<ProductSummary> search(@ModelAttribute @Valid ProductSearchCriteria criteria,
10 @PageableDefault(size = 20, sort = "createdAt", direction = Sort.Direction.DESC)
11 Pageable pageable) {
12 return productQueryService.search(criteria, pageable);
13 }
14 
15 @Getter
16 @Setter
17 public static class ProductSearchCriteria {
18 
19 private String keyword;
20 
21 private Set<Long> categoryIds = new HashSet<>();
22 
23 @Valid
24 private PriceRange price = new PriceRange();
25 
26 @DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
27 private LocalDate releasedAfter;
28 
29 private boolean inStockOnly;
30 
31 public boolean hasKeyword() {
32 return StringUtils.hasText(keyword);
33 }
34 }
35 
36 @Getter
37 @Setter
38 public static class PriceRange {
39 
40 @PositiveOrZero
41 private BigDecimal min;
42 
43 @Positive
44 private BigDecimal max;
45 
46 @AssertTrue(message = "price.max must be greater than or equal to price.min")
47 public boolean isRangeValid() {
48 return min == null || max == null || max.compareTo(min) >= 0;
49 }
50 }
51}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1@ModelAttribute binds flat query parameters into a nested object graph, so complex filters stay strongly typed.
  2. 2@Valid with bean-validation constraints lets you reject bad requests declaratively, including cross-field checks via @AssertTrue.
  3. 3Accepting a Pageable with @PageableDefault gives clients paging and sorting control while guaranteeing safe defaults.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Binding paged search filters in Spring — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code