jmk*_*een 6 java validation jax-rs jaxb
我们使用JAX-RS一些相当基本的POJO的实体,具有许多@GET和@POST注解的方法是@Produce和@Consume MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML.没什么了不起的.
我的问题是我应该如何最好地验证进来的数据?
我们没有XML Schema,尽管我可以生成一个.我需要以某种方式挂钩这看起来不太吸引人,我还没有找到一个简洁的例子.
我们可以使用"bean验证",但我再次不确定如何将其挂钩并调用它.
最后(我认为)我们可以为isValidForXXX()实体POJO 添加一些方法,并在我们有一个交给我们的实例时调用它们.
有人建议吗?
如果您有 XML 模式,那么您可以在MessageBodyReader. 具体示例请参阅我对类似问题的回答。
验证读者
下面是一个简单的实现,MessageBodyReader它执行四件事:1) Create a JAXBContext、2) 创建 的实例Schema、3) 设置 的架构Unmarshaller4) 解组InputStream。
package org.example;
import java.io.*;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.net.URL;
import javax.ws.rs.*;
import javax.ws.rs.core.*;
import javax.ws.rs.ext.*;
import javax.xml.XMLConstants;
import javax.xml.bind.*;
import javax.xml.validation.*;
@Provider
@Consumes("application/xml")
public class ValidatingReader implements MessageBodyReader<Customer> {
@Context
protected Providers providers;
private Schema schema;
private JAXBContext jaxbContext;
public ValidatingReader() {
try {
JAXBContext jc = JAXBContext.newInstance(Customer.class);
SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
URL schemaURL = null; // URL for your XML schema
schema = sf.newSchema(schemaURL);
} catch(Exception e) {
throw new RuntimeException(e);
}
}
public boolean isReadable(Class<?> arg0, Type arg1, Annotation[] arg2, MediaType arg3) {
return arg0 == Customer.class;
}
public Customer readFrom(Class<Customer> arg0, Type arg1, Annotation[] arg2, MediaType arg3, MultivaluedMap<String, String> arg4, InputStream arg5)
throws IOException, WebApplicationException {
try {
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
unmarshaller.setSchema(schema);
return (Customer) unmarshaller.unmarshal(arg5);
} catch(JAXBException e) {
throw new RuntimeException(e);
}
}
}
Run Code Online (Sandbox Code Playgroud)