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
java
@Service public class InventoryService { private final RestClient warehouseClient;
Bulkhead-protected HTTP calls in Spring
bulkhead
resilience
fallback
Intermediate
7 steps
go
func UploadDocument(c *gin.Context) { fileHeader, err := c.FormFile("file") if err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": "file is required"})
Handling multipart uploads in Gin
multipart-upload
validation
error-handling
Intermediate
9 steps
java
@Configuration public class DataSourceLoggingConfig { @Bean
Wrapping a Spring DataSource for query tracing
proxy pattern
observability
data source
Intermediate
7 steps
python
import base64 import json from typing import Annotated, Optional
Cursor pagination in a FastAPI endpoint
pagination
cursor
async
Intermediate
9 steps
java
@Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Constraint(validatedBy = PasswordsMatchValidator.class) public @interface PasswordsMatch {
Custom cross-field validation in Spring
bean-validation
custom-constraints
cross-field-validation
Intermediate
8 steps
java
public final class LogRedactor { private static final Pattern SECRET = Pattern.compile( "(?i)(password|token|api[_-]?key|secret|authorization)\\s*[=:]\\s*\\S+");
Streaming log redaction in Java
regex
streaming-io
try-with-resources
Intermediate
9 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.