在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異常,全局異常處理器會捕獲該異常并返回錯誤信息。