java 39 lines · 8 steps

Validating query params in a Spring controller

A Spring REST endpoint that validates paginated search parameters and reports violations as clean JSON.

Explained by highlit
1@RestController
2@RequestMapping("/api/products")
3@Validated
4public class ProductSearchController {
5 
6 private final ProductService productService;
7 
8 public ProductSearchController(ProductService productService) {
9 this.productService = productService;
10 }
11 
12 @GetMapping
13 public Page<ProductSummary> search(
14 @RequestParam @NotBlank @Size(max = 100) String query,
15 @RequestParam(defaultValue = "0") @Min(0) int page,
16 @RequestParam(defaultValue = "20") @Min(1) @Max(100) int size,
17 @RequestParam(required = false) @DecimalMin("0.0") BigDecimal minPrice,
18 @RequestParam(required = false) @Pattern(regexp = "ASC|DESC") String direction) {
19 
20 Sort.Direction sortDir = direction == null
21 ? Sort.Direction.ASC
22 : Sort.Direction.valueOf(direction);
23 Pageable pageable = PageRequest.of(page, size, Sort.by(sortDir, "price"));
24 return productService.search(query, minPrice, pageable);
25 }
26 
27 @ExceptionHandler(ConstraintViolationException.class)
28 @ResponseStatus(HttpStatus.BAD_REQUEST)
29 public Map<String, String> handleConstraintViolations(ConstraintViolationException ex) {
30 return ex.getConstraintViolations().stream()
31 .collect(Collectors.toMap(
32 v -> {
33 String path = v.getPropertyPath().toString();
34 return path.substring(path.lastIndexOf('.') + 1);
35 },
36 ConstraintViolation::getMessage,
37 (first, second) -> first));
38 }
39}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1@Validated on the class activates method-level bean validation for individual @RequestParam values.
  2. 2PageRequest lets you turn raw page, size, and sort inputs into a reusable Pageable for the service layer.
  3. 3A local @ExceptionHandler converts validation failures into a tidy field-to-message map instead of a stack trace.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Validating query params in a Spring controller — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code