JAX-RS: Request validation using XSD, JAXB

2020-07-22 09:18发布

问题:

Tech Stack: Java 1.6, JAXB, Spring 3, JAX-RS (RESTEasy)

I've written a web service (REST) and now I want to validate the request using a schema. I've a working code as seen here for validation.

My code looks like this:

public abstract class AbstractValidatingReader<T> implements MessageBodyReader<T> {

    @Context
    protected Providers providers;

    private Schema schema;

    public AbstractValidatingReader() {
       ....
    }

    @SuppressWarnings("unchecked")
    @Override
    public boolean isReadable(Class<?> arg0, Type arg1, Annotation[] arg2, MediaType arg3) {
        ....
        return arg0 == readableClass;
    }

    @SuppressWarnings("unchecked")
    @Override
    public T readFrom(Class<T> arg0, Type arg1, Annotation[] arg2, MediaType arg3, MultivaluedMap<String, String> arg4,
            .....
        return type;
    }

    protected abstract T validate(T arg0) throws WebApplicationException;
}

and,

@Component
@Provider
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.APPLICATION_XAMF })
public class ValidatingReaderImpl extends AbstractValidatingReader<Person> {

    @Override
    protected Person validate(Person arg0) throws WebApplicationException {

        return arg0;
    }

}

This works fine for Person class and the request is getting validated. But, I've many other requests e.g. Contacts, Links, Employment etc.

Do I have to extend the AbstractValidatingReader class for each request type?

I am validating against the same schema, so looks like lot of code\classes for doing this.

Thanks, Adi