Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Interview question

How do you validate request bodies in Spring Boot? स्प्रिंग बूट में रिक्वेस्ट बॉडी को कैसे वैलिडेट करें?

Answer

Spring Boot integrates with Bean Validation (JSR-380 / Jakarta Validation) via spring-boot-starter-validation. Constraints like @NotNull, @NotBlank, @Size, and @Email are placed on a DTO's fields, and the controller method parameter is annotated with @Valid or @Validated so Spring runs the checks automatically before the method body executes.

If validation fails, Spring throws a MethodArgumentNotValidException, which is typically caught in a @ControllerAdvice to return a structured 400 Bad Request response with field-level error messages.

public class UserDto {
    @NotBlank private String name;
    @Email private String email;
}

@PostMapping
public User create(@Valid @RequestBody UserDto dto) { ... }

स्प्रिंग बूट, spring-boot-starter-validation के ज़रिए Bean Validation (JSR-380 / Jakarta Validation) के साथ इंटीग्रेट होता है। @NotNull, @NotBlank, @Size, और @Email जैसे कंस्ट्रेंट्स को DTO के फील्ड्स पर रखा जाता है, और कंट्रोलर मेथड पैरामीटर को @Valid से एनोटेट किया जाता है ताकि स्प्रिंग मेथड बॉडी चलने से पहले जाँच स्वचालित रूप से चलाए।

यदि वैलिडेशन फेल होता है, तो स्प्रिंग MethodArgumentNotValidException फेंकता है, जिसे आमतौर पर @ControllerAdvice में पकड़कर फील्ड-स्तर की एरर मैसेज के साथ 400 Bad Request रिस्पॉन्स दिया जाता है।

public class UserDto {
    @NotBlank private String name;
    @Email private String email;
}

@PostMapping
public User create(@Valid @RequestBody UserDto dto) { ... }

Was this answer clear?