4

我正在春天创建一个网络服务。我有一个嵌套在我的 OtherParentDTO 中的 Params DTO。每个请求可能仅包含参数 Dto 中的某些字段。如果存在这些字段,那么我需要进行验证(基本上是空检查)。在自定义验证器中,我将指定需要为特定请求验证哪些字段。我的问题是在控制器中错误字段作为参数返回。有什么方法可以将其更改为 params.customerId 或 parmas.userId。

更新客户要求:

{"params":{"customerId" : "b2cab997-df13-4cb0-8f67-4357b019bb96"}, "customer":{}}

更新用户请求:

{"params":{"userId" : "b2cab997-df13-4cb0-8f67-4357b019bb96"}, "user":{}}

@JsonSerialize(include = Inclusion.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public class Params {

    private String customerId;
    private String userId;

    //setter and getter are there
}

public class UpdateCustomerRequestDTO {

    @NotNull
    @IsValid(params = {"customerId"}) 
    protected Params params;
    @NotNull @Valid
    private Customer customer;
}

public class UpdateUserRequestDTO {

    @NotNull
    @IsValid(params = {"userId"}) 
    protected Params params;
    @NotNull @Valid
    private User user;
}

自定义约束验证器

@Constraint(validatedBy = {RequestParamsValidator.class})
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface IsValid {
    String[] params() default "";
    String message() default "{com.test.controller.validator.IsValid.message}";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
}

public class RequestParamsValidator implements ConstraintValidator<IsValid, Params> {

    /* (non-Javadoc)
     * @see javax.validation.ConstraintValidator#initialize(java.lang.annotation.Annotation)
     */
    @Override
    public void initialize(IsValid constraintAnnotation) {
        validateItems = constraintAnnotation.params();
    }

    /* (non-Javadoc)
     * @see javax.validation.ConstraintValidator#isValid(java.lang.Object, javax.validation.ConstraintValidatorContext)
     */
    @Override
    public boolean isValid(Params value, ConstraintValidatorContext context) {
        try {
            for (String reqItem : validateItems) {
                final Object curObj = PropertyUtils.getProperty(value, reqItem);
                if (curObj == null || curObj.toString().isEmpty()) {    
                    return false;
                }
            }
        } catch (final Exception ignore) {
            // ignore
        }
        return true;
    }
}

控制器

@RequestMapping(method = RequestMethod.POST, value="", produces="application/json")
    public @ResponseBody BaseResponseDTO updateCustomer(@RequestBody @Valid UpdateCustomerRequestDTO requestDTO,
            BindingResult result) throws Exception {

        if (result.hasErrors()) {
            log.error("[Field] "+result.getFieldError().getField()+" [Message]"+ result.getFieldError().getDefaultMessage())
            // But here the result.getFieldError().getField() is returning params. Is there any way with which I can change it to params.customerId/parmas.userId
            return false
        }
        // add customer logic
    }
4

0 回答 0