gpt4 book ai didi

spring-mvc - 一起使用@Valid 和@InitBinder 进行Spring Rest 验证

转载 作者:行者123 更新时间:2023-12-05 07:49:43 25 4
gpt4 key购买 nike

我有一个 spring REST 应用程序,我想使用 @Valid 注释来装饰可以为简单的 @NotNull 检查进行验证的 bean 字段。

public ResponseEntity<ExtAuthInquiryResponse> performExtAuthInq(@Valid @RequestBody ExtAuthInquiryRequest extAuthInquiryRequest)

像这样

 @NotBlank(message = "requestUniqueId cannot be blank..")
private String requestUniqueId;

除此之外,我想使用@initBinder 进行更复杂的验证(比如基于一个字段的值,第二个字段是强制性的)

 @InitBinder("extAuthInquiryRequest")
protected void initExtAuthInqRequestBinder(WebDataBinder binder) {
binder.setValidator(extAuthInqValidator);
}

这是验证器实现(仅适用于条件验证情况)

@Override
public void validate(Object target, Errors e) {

ExtAuthInquiryRequest p = (ExtAuthInquiryRequest) target;
// Dont want to do this check here. Can be simply done in the bean using @NotNull checks
ValidationUtils.rejectIfEmpty(e, "requestUniqueId", "requestUniqueId is empty");


// this is a good candidate to be validated here
if(StringUtils.isNotBlank(p.getPersonInfo().getContactInfo().getPhoneNumber().getPhoneType())){
if(StringUtils.isBlank(p.getPersonInfo().getContactInfo().getPhoneNumber().getPhoneNumber())){
e.rejectValue("personInfo.contactInfo.phoneNumber.phoneNumber", "phoneNumber is mandatory when phoneType is provided");
}
}
}

我在网上看到了一堆使用其中一个或另一个的示例。我曾尝试同时使用这两种方法,但是当我设置了@initBinder 时,请求对象上的@valid 注释不再受尊重。

因为我不想在 spring 验证器类中编写代码来进行简单的 @NotNull 检查。有没有办法一起做这两种方法。

最佳答案

关于spring-mvc - 一起使用@Valid 和@InitBinder 进行Spring Rest 验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36990528/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com