我们将 JAX-RS 与一些相当基本的 POJO 实体一起使用,并且有许多 @GET
和 @POST
注释方法,@Produce
和 @Consume
MediaType.APPLICATION_JSON
,MediaType.APPLICATION_XML
。没什么了不起的。
我的问题是我应该如何最好地验证传入的数据?
我们没有 XML 架构,但我可以生成一个。我需要以某种方式将它 Hook ,这看起来不太吸引人,而且我还没有找到一个简洁的例子。
我们可以使用“bean 验证”,但我再次不确定如何连接并调用它。
最后(我认为)我们可以向实体 POJO 添加一些 isValidForXXX()
方法,并在我们有实例提交给我们时调用它们。
有人推荐吗?
最佳答案
如果您有 XML 模式,则可以在 MessageBodyReader
中使用 JAXB 验证。有关具体示例,请参阅我对类似问题的回答。
验证阅读器
下面是 MessageBodyReader
的基本实现,它做了四件事:1) 创建 JAXBContext
,2) 创建 Schema
的实例, 3) 在 Unmarshaller
上设置架构 4) 解码 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);
}
}
}
关于java - 使用 JAX-RS 对 JAXB 数据进行实际验证?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10398119/