SpringBoot Request Parameter Validation Guide
In Spring Boot, you can utilize annotations from the JSR 303 specification to validate request parameters. The specific steps are as follows:
- Add validation annotations like @Validated and @NotBlank before the request method parameters in the Controller class.
@RestController
@RequestMapping("/api")
@Validated
public class UserController {
@PostMapping("/user")
public ResponseEntity<String> createUser(@Valid @RequestBody UserDto userDto) {
// 处理请求参数
return ResponseEntity.ok("User created successfully");
}
}
- Create a DTO class to encapsulate request parameters, and add validation annotations to the properties of the DTO class.
public class UserDto {
@NotBlank(message = "Name is mandatory")
private String name;
@Email(message = "Email should be valid")
private String email;
// getter and setter
}
- Define a global exception handler in the Controller class to capture validation errors and return error messages.
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
public ResponseEntity<String> handleValidationException(MethodArgumentNotValidException ex) {
BindingResult result = ex.getBindingResult();
List<String> errorMessages = result.getAllErrors().stream()
.map(DefaultMessageSourceResolvable::getDefaultMessage)
.collect(Collectors.toList());
return ResponseEntity.badRequest().body(String.join(", ", errorMessages));
}
}
In this way, when the validation of the request parameters fails, the corresponding error message will be returned. Spring Boot automatically validates the request parameters and throws a MethodArgumentNotValidException exception when the validation fails, the global exception handler will capture this exception and return the error message.