如何在Spring Boot中验证Rest请求

时间:2019-01-21 16:00:51

标签: java validation spring-boot

我正在尝试根据某些字段的存在来验证我的休息请求。例如,如果transactionDate字段为null或在我的请求对象中不存在,我想向客户端抛出错误。

尽管有本指南的内容,我还是无法做到,但我的请求仍然可以传递给控制器​​。

How can I validate two or more fields in combination?

DTO

@FraudRestRequestValidator
public class FraudActionsRestRequest {
private BigDecimal amount;
    private String receiverTransactionDate;
    private String receiverNameSurname;
    private BigDecimal exchangeRate;
    private String transactionReferenceNumber;
    @NotNull
    private String transactionDate;
    @NotNull
    private String transactionTime;
    private String transactionTimeMilliseconds;
    private BigDecimal tlAmount;
    private String channel;
}

注释

@Constraint(validatedBy = FraudActionsRestValidator.class)
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface FraudRestRequestValidator {
    String message() default "Invalid Limit of Code";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
}

VALIDATOR

public class FraudActionsRestValidator implements ConstraintValidator<FraudRestRequestValidator, FraudActionsRestRequest> {

    @Override
    public void initialize(FraudRestRequestValidator constraintAnnotation) {

    }

    @Override
    public boolean isValid(FraudActionsRestRequest fraudActionsRestRequest, ConstraintValidatorContext constraintValidatorContext) {
        //I will implement my logic in future
        return false;
    }
}

REST CONTROLLER

@PostMapping("/getFraudActions")
    public ResponseEntity<?> getFraudActions(@Valid @RequestBody FraudActionsRestRequest fraudActionsRestRequest, Errors errors) throws Exception

谢谢。

2 个答案:

答案 0 :(得分:1)

看起来一切正常。

您可能在其余控制器类上缺少@Validated注释,

有关更多信息,请参见https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-validation.html

答案 1 :(得分:1)

在您的自定义验证器中,只需实现您想要的逻辑即可。您做了所有正确的事情,除了一些小事情:

@Constraint(validatedBy = FraudActionsRestValidator.class)
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface ValidFraudRestRequest {
    String message() default "Invalid Limit of Code";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
}

public class FraudActionsRestValidator implements ConstraintValidator<ValidFraudRestRequest, FraudActionsRestRequest> {

    @Override
    public void initialize(ValidFraudRestRequest constraintAnnotation) {

    }

    @Override
    public boolean isValid(FraudActionsRestRequest fraudActionsRestRequest, ConstraintValidatorContext constraintValidatorContext) {

        return fraudActionsRestRequest.getTransactionDate() != null && fraudActionsRestRequest.getTransactionTime() != null && additional check you need;
    }
}