简体   繁体   English

是否有机会验证请求正文中 DTO Object 的所有值是 null

[英]Is there any chance to validate all the values of the DTO Object is null in Request Body

@Controller......

@PutMapping(value = "/{id}")
    public ResponseEntity<JsonNode> editStudent( @PathVariable @Positive(message = "Student id must be Positive Value") Long id, @Valid @ValidRequestBody(DTOClass = StudentDTO.class) @Validated(value = Update.class) @RequestBody(required = true) StudentDTO studentDTO, BindingResult bindingResult ) {.....

----------------------------------------------------------------------------

@Documented
@Retention(RUNTIME)
@Target({ TYPE, ElementType.METHOD, ElementType.PARAMETER, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.FIELD, ElementType.LOCAL_VARIABLE, ElementType.MODULE, ElementType.PACKAGE, ElementType.TYPE_PARAMETER, ElementType.TYPE_USE })
@Constraint(validatedBy = RequestBodyValidator.class)
public @interface ValidRequestBody {

    String message()

    default "Required parameter is missing";

    Class<?>[] groups() default {};

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

    Class<?> DTOClass();
}

-----------------------------------------------------

public class RequestBodyValidator implements ConstraintValidator<ValidRequestBody, Map<String, Object>> {

    Class<?> dtoClass = null;

    @Override
    public void initialize( ValidRequestBody constraintAnnotation ) {

        this.dtoClass = constraintAnnotation.DTOClass();
    }

    @Override
    public boolean isValid( Map<String, Object> objectNode, ConstraintValidatorContext context ) {

        Collection<Object> objectValues = objectNode.values();

        return !objectValues.stream().allMatch( null );
    }
}

You can use @Valid or @NonNull annotation on all fields in your DTO.您可以在 DTO 中的所有字段上使用 @Valid 或 @NonNull 注释。 So, if a field is received as null or empty, exception would be thrown.因此,如果接收到的字段为 null 或为空,则会引发异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM