简体   繁体   English

Dropwizard API资源中的@Valid

[英]@Valid in dropwizard API resource

I am trying to use @Valid in dropwizard before the object is consumed by the API. 我试图在API消耗对象之前在dropwizard中使用@Valid。 However, none of the attributes of the object are getting validated as it seems validation is not happening? 但是,对象的所有属性都没有得到验证,因为似乎没有进行验证? Am I missing something in adding a configuration to enable it? 添加配置以启用它时,我是否缺少某些功能?

FYI: We have implemented our own message body reader which extends from javax.ws.rs.ext.MessageBodyReader for mapping JSON to object. 仅供参考:我们已经实现了自己的消息正文阅读器,它从javax.ws.rs.ext.MessageBodyReader扩展而来,用于将JSON映射到对象。

You need to store a javax.validation.Validator object in your MessageBodyReader and use it to validate classes annotated with @Valid in your readFrom() method. 您需要在MessageBodyReader中存储一个javax.validation.Validator对象,并使用它来验证readFrom()方法中以@Valid注释的类。 This is how Dropwizard's Jackson Provider does it. 这就是Dropwizard的Jackson Provider所做的。

So the code looks something like this: 所以代码看起来像这样:

private static final Class<?>[] DEFAULT_GROUP_ARRAY = new Class<?>[]{ Default.class };
private final XmlMapper mapper;
private final Validator validator;

public MyMessageBodyReader(XmlMapper mapper, Validator validator) {
    this.validator = validator;
    this.mapper = mapper;
    setMapper(mapper);
}

@Override
public Object readFrom(Class<Object> type,
                       Type genericType,
                       Annotation[] annotations,
                       MediaType mediaType,
                       MultivaluedMap<String, String> httpHeaders,
                       InputStream entityStream) throws IOException {
    return validate(annotations, super.readFrom(type,
            genericType,
            annotations,
            mediaType,
            httpHeaders,
            entityStream));
}

private Object validate(Annotation[] annotations, Object value) {
    final Class<?>[] classes = findValidationGroups(annotations);

    if (classes != null) {
        final Set<ConstraintViolation<Object>> violations = validator.validate(value, classes);
        if (!violations.isEmpty()) {
            throw new ConstraintViolationException("The request entity had the following errors:",
                    ConstraintViolations.copyOf(violations));
        }
    }

    return value;
}

private Class<?>[] findValidationGroups(Annotation[] annotations) {
    for (Annotation annotation : annotations) {
        if (annotation.annotationType() == Valid.class) {
            return DEFAULT_GROUP_ARRAY;
        } else if (annotation.annotationType() == Validated.class) {
            return  ((Validated) annotation).value();
        }
    }
    return null;
}

I have an example here , where I've written a custom XML Jackson Reader + Writer with Validation support. 我在这里有一个示例,其中我编写了一个带有验证支持的自定义XML Jackson Reader + Writer。

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

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