在 Java Spring boot 中,我制作了類自定義驗證器。如果驗證器中的一個欄位失敗,我總是會收到兩條錯誤訊息
[“WRONG_CAR_COLOR”、“WRONG_YEAR_OF_PRODUCTION”]
public class ElectricCarSpecValidator implements ConstraintValidator<ElectricCarSpec, CreateCarCommand> {
private static final Integer minYearOfProduction = 2000;
private static final Integer carColorRed = 10;
private static final Integer electricCarId = 5;
@Override
public boolean isValid(CreateCarCommand command, ConstraintValidatorContext context) {
if (!command.getFuelTypeId().equals(electricCarId)) {
return true;
}
return command.getYearOfProduction() >= minYearOfProduction && !command.getCarColorId().equals(carColorRed);
}
驗證器:
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity handleMethodArgumentNotValid(MethodArgumentNotValidException ex) {
List<String> errors = ex.getAllErrors().stream()
.map(DefaultMessageSourceResolvable::getDefaultMessage)
.collect(Collectors.toList());
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(errors);
}
注釋:
@ElectricCarSpec.List({
@ElectricCarSpec(field = "yearOfProduction", message = "WRONG_YEAR_OF_PRODUCTION"),
@ElectricCarSpec(field = "carColorId", message = "WRONG_CAR_COLOR")
})
uj5u.com熱心網友回復:
問題是無論你指定什么欄位,你總是做同樣的驗證——檢查兩個欄位是否有效。
return command.getYearOfProduction() >= minYearOfProduction
&& !command.getCarColorId().equals(carColorRed);
為了考慮您的field屬性,您需要覆寫initialize(A constraintAnnotation)。檔案保證在之前呼叫它isValid。
初始化驗證器以準備 isValid(Object, ConstraintValidatorContext) 呼叫。傳遞給定約束宣告的約束注釋。保證在使用此實體進行驗證之前呼叫此方法。
像這樣的東西:
public class TestConstraintValidator implements ConstraintValidator<ElectricCarSpec, CreateCarCommand> {
private String field;
@Override
public void initialize(ElectricCarSpec constraintAnnotation) {
this.field = constraintAnnotation.field();
}
@Override
public boolean isValid(CreateCarCommand value, ConstraintValidatorContext context) {
if (field.equals("yearOfProduction")) {
//validate year of production
}
if (field.equals("carColorId")) {
//validate color id
}
return true;
}
}
if為每個要驗證的欄位設定幾個s 很好,但是如果要檢查的欄位太多,您可以考慮撰寫策略模式來根據欄位名稱選擇正確的驗證策略。
uj5u.com熱心網友回復:
而不是實施ConstraintValidator,你應該實施org.springframework.validation.Validator。它包含一種validate方法,您可以在其中分別驗證多個欄位,例如
public void validate(Object target, Errors errors) {
CreateCarCommand createCarCommand = (CreateCarCommand) target;
if (!command.getFuelTypeId().equals(electricCarId)) {
return;
}
if(command.getYearOfProduction() < minYearOfProduction) {
errors.rejectValue("yearOfProduction", "WRONG_YEAR_OF_PRODUCTION");
}
if(!command.getCarColorId().equals(carColorRed)) {
errors.rejectValue("carColorId", "WRONG_CAR_COLOR");
}
}
在控制器類中,宣告驗證器,如
@Autowired
//@Qualifier("ElectricCarSpecValidator") //use if multiple implementations
private Validator electricCarSpecValidator;
在控制器方法中,
electricCarSpecValidator.validate(createCarCommand, bindingResult);
if(bindingResult.hasErrors()) {
//Errors found
model.addAttribute("org.springframework.validation.BindingResult.createCarCommand", bindingResult);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/513240.html
標籤:爪哇弹簧靴验证
