Request Validation: Guarding the Door

Request Validation: Guarding the Door in Java: Every byte arriving from a client is untrusted.

Concept Explanation

Every byte arriving from a client is untrusted. A price could be negative, an email could be "asdf", a required name could be missing entirely. Validating at the edge means the rest of your code can assume the data is sane.

Spring uses Jakarta Bean Validation — you annotate the fields, and Spring enforces them before your method body runs.


Annotating a DTO

public class CreateProductRequest {

    @NotBlank(message = "Name is required")
    @Size(max = 100, message = "Name must be 100 characters or fewer")
    private String name;

    @NotNull(message = "Price is required")
    @DecimalMin(value = "0.01", message = "Price must be positive")
    private BigDecimal price;

    @Email(message = "Must be a valid email address")
    private String contactEmail;

    @Min(0) @Max(10_000)
    private int stock;

    // getters and setters
}

Triggering It

The @Valid annotation is what actually runs the checks:

@PostMapping("/products")
public ResponseEntity<Product> create(@Valid @RequestBody CreateProductRequest request) {
    Product saved = service.create(request);
    return ResponseEntity.status(HttpStatus.CREATED).body(saved);
}

If validation fails, Spring throws MethodArgumentNotValidException and your method is never called.

Validate path and query parameters too — this needs @Validated on the class:

@RestController
@Validated
public class ProductController {

    @GetMapping("/products/{id}")
    public Product byId(@PathVariable @Min(1) Long id) { ... }
}

Returning Useful Errors

The default error body is noisy. Flatten it into field-to-message pairs:

@RestControllerAdvice
public class ValidationHandler {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Map<String, String> onInvalid(MethodArgumentNotValidException ex) {
        Map<String, String> errors = new HashMap<>();
        ex.getBindingResult().getFieldErrors()
          .forEach(e -> errors.put(e.getField(), e.getDefaultMessage()));
        return errors;
    }
}

The client now receives {"price": "Price must be positive"} — actionable instead of cryptic.


Common Mistakes

  1. Forgetting @Valid: The annotations are present, nothing is enforced, and the bug looks like Spring is broken.
  2. Validating the entity instead of a DTO: Ties your API contract to your database schema. Keep them separate.
  3. Missing the validation starter: Without spring-boot-starter-validation, the annotations are silently inert.
  4. Trusting client-side validation: A browser check is a courtesy. Anyone can curl your endpoint directly.

Best Practices

  • Always write a message: Default messages are generic and leak implementation details.
  • Separate DTOs from entities: Different concerns, different shapes, different lifetimes.
  • Validate at the boundary only: Once past the controller, code should not re-check the same invariants.

Practice Exercises

  1. The Rejected Payload: Build a DTO with four constraints and curl an invalid body. Confirm the controller body never executes.
  2. The Flat Error Map: Add the @RestControllerAdvice above and compare the response with Spring's default.
  3. The Custom Constraint: Write a @ValidSku annotation that only accepts strings matching [A-Z]{3}-\\d{4}.