gpt4 book ai didi

java - 如何在 Spring Boot 中验证 Rest 请求

转载 作者:行者123 更新时间:2023-12-02 01:42:17 27 4
gpt4 key购买 nike

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

尽管有本指南的来源,但我无法做到这一点,但我的请求仍然可以在 Controller 中传递。

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;
}
}

休息 Controller

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

谢谢。

最佳答案

在您的自定义 validator 中,只需实现您想要的逻辑即可。除了一些小事情之外,您所做的一切都是正确的:

@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;
}
}

关于java - 如何在 Spring Boot 中验证 Rest 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54293603/

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