约束验证对于Rest Api请求不起作用。

huangapple 未分类评论45阅读模式
英文:

ConstraintValidation Not Working for a Rest Api Request

问题

我创建了一个API,并添加了一个自定义注解来验证请求体对象,但这从未被调用过。以下是对象。请查看代码并帮助我找出需要修正的地方?

@NotNull, @Size 也不起作用

请求体对象

@Getter
@AllArgsConstructor
@Sample
public class SaleRequest {
    @NotNull
    private Integer sale;
    @NotNull
    private Date dateTime;
    @NotNull
    @Size(min = 10, max = 10)
    private String customerId;
}

注解

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = {SalesRequestValidator.class})
@Documented
public @interface Sample {
    Class<?>[] groups() default { };

    Class<? extends Payload>[] payload() default { };

    String message() default "Invalid Sale Request";
}

验证器

public class SalesRequestValidator implements ConstraintValidator<Sample, SaleRequest> {
    private String message;

    @Override
    public void initialize(Sample constraintAnnotation) {
        this.message = constraintAnnotation.message();
    }

    @Override
    public boolean isValid(SaleRequest sale, ConstraintValidatorContext context) {
        System.out.println("Tested!");
        return sale.getSale() > 0;
    }
}

API 实现

public interface SalesApi {
    @RequestMapping(
            value = {"/sales"},
            produces = {"application/json"},
            consumes = {"application/json"},
            method = {RequestMethod.POST}
    )
    ResponseEntity<Integer> submitSale(@RequestBody @Valid SaleRequest saleRequest);
}

找不出问题出在哪里。

英文:

I created an API and added an custom-annotation to validate the Request body object, but this was never getting called. Below is the Object. Please go through the code and help me out where the code need to be corrected?

@NotNull, @Size is also not working

Request Body Object

@Getter
@AllArgsConstructor
@Sample
public class SaleRequest {
    @NotNull
    private Integer sale;
    @NotNull
    private Date dateTime;
    @NotNull
    @Size(min = 10, max = 10)
    private String customerId;
}

Annotation

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = {SalesRequestValidator.class})
@Documented
public @interface Sample {
    Class&lt;?&gt;[] groups() default { };

    Class&lt;? extends Payload&gt;[] payload() default { };


    String message() default &quot;Invalid Sale Request&quot;;
}

Validator

public class SalesRequestValidator implements ConstraintValidator&lt;Sample, SaleRequest&gt; {
    private String message;

    @Override
    public void initialize(Sample constraintAnnotation) {
        this.message = constraintAnnotation.message();
    }

    @Override
    public boolean isValid(SaleRequest sale, ConstraintValidatorContext context) {
        System.out.println(&quot;Tested!&quot;);
        return sale.getSale() &gt; 0;
    }

}

Api Implementation

public interface SalesApi {
    @RequestMapping(
            value = {&quot;/sales&quot;},
            produces = {&quot;application/json&quot;},
            consumes = {&quot;application/json&quot;},
            method = {RequestMethod.POST}
    )
    ResponseEntity&lt;Integer&gt; submitSale(@RequestBody @Valid SaleRequest saleRequest);
  }

Could not figure where I went wrong

答案1

得分: 0

实现看起来还不错。

确保您在控制器方法中设置了@Valid注解,您希望在其中接收SaleRequest的请求体。

它应该类似于这样:
addNewSaleRequest(@RequestBody @Valid SaleRequest saleRequest)

英文:

Implementation looks ok.

Make sure you have set the @Valid annotation in your controller method where you expect to receive the request body of SaleRequest.

It should look something like this:
addNewSaleRequest(@RequestBody @Valid SaleRequest saleRequest)

答案2

得分: 0

尝试将 @Target({ElementType.TYPE}) 扩展为 ElementType.PARAMETER,因为您希望使用它来验证方法参数。相关的控制器上也需要添加 @Validated 注解。

英文:

Try to extend @Target({ElementType.TYPE}) with ElementType.PARAMETER as you want to validate a method parameter with it.
A @Validated annotation is needed on the related Controller as well.

huangapple
  • 本文由 发表于 2020年4月6日 19:01:10
  • 转载请务必保留本文链接:https://java.coder-hub.com/61058272.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定