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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1@Validated on the class activates method-level bean validation for individual @RequestParam values.
- 2PageRequest lets you turn raw page, size, and sort inputs into a reusable Pageable for the service layer.
- 3A local @ExceptionHandler converts validation failures into a tidy field-to-message map instead of a stack trace.
Related explainers
typescript
import { registerLocaleData } from '@angular/common'; import localeFr from '@angular/common/locales/fr'; import localeFrExtra from '@angular/common/locales/extra/fr'; import localeDe from '@angular/common/locales/de';
Locale-aware bootstrapping in Angular
i18n
localization
dependency-injection
Intermediate
8 steps
typescript
import { Module } from '@nestjs/common'; import { ConfigModule } from '@nestjs/config'; import * as Joi from 'joi';
Validating env config at boot in NestJS
configuration
schema-validation
environment-variables
Intermediate
8 steps
php
<?php namespace App\Services\Checkout;
Validating coupons with Laravel's Pipeline
pipeline
chain of responsibility
transactions
Intermediate
7 steps
java
@Component @Converter public class EncryptedStringConverter implements AttributeConverter<String, String> {
Transparent column encryption in Spring & JPA
encryption
aes-gcm
jpa-converter
Advanced
10 steps
typescript
import { Inject, Injectable, Logger } from '@nestjs/common'; import { CACHE_MANAGER } from '@nestjs/cache-manager'; import { Cache } from 'cache-manager'; import { InjectRepository } from '@nestjs/typeorm';
A cache-aside country lookup in NestJS
cache-aside
dependency-injection
batch-lookup
Intermediate
8 steps
php
<?php namespace App\Services;
How a password strength validator works in PHP
validation
regular-expressions
data-driven
Intermediate
8 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/validating-query-params-in-a-spring-controller-explained-java-1d03/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.