在Spring Boot中,可以使用JSR 303规范中的注解来实现请求参数的校验。具体步骤如下:
@RestController
@RequestMapping("/api")
@Validated
public class UserController {
@PostMapping("/user")
public ResponseEntity<String> createUser(@Valid @RequestBody UserDto userDto) {
// 处理请求参数
return ResponseEntity.ok("User created successfully");
}
}
public class UserDto {
@NotBlank(message = "Name is mandatory")
private String name;
@Email(message = "Email should be valid")
private String email;
// getter and setter
}
@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));
}
}
这样,当请求参数校验失败时,会返回相应的错误信息。Spring Boot会自动校验请求参数,并在校验失败时抛出MethodArgumentNotValidException异常,全局异常处理器会捕获该异常并返回错误信息。