根据 xsd/生成的对象验证对象
Validate object against xsd / generated object
我有一个应用程序,其中我从 xsd 模式生成了 Java classes。我还有一个使用 jax-rs 的休息服务。我需要验证 POST 方法的输入,以确保符合 xsd 模式中设置的规则。
@POST
@Path("/person/add")
public void addPerson(Person person) {
//Need to validate Person object
daoManager.addPersonToDB(person);
}
Person 对象是从 xsd 生成的 class。我可以假设该对象符合 xsd,还是我必须验证该对象?在那种情况下,我该如何验证?
我知道这是一个新手问题,但我希望有人能提供帮助。
我自己还没有尝试过,但我认为下面的代码会起作用。
JAXBContext context = JAXBContext.newInstance(Person.class);
Marshaller marshaller = context.createMarshaller();
根据你的命名空间,使用
marshaller.setProperty(Marshaller.JAXB_NO_NAMESPACE_SCHEMA_LOCATION, "yourXSD.xsd");
或
marshaller.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, "yourXSD.xsd");
然后编组person实例,如果没有异常,说明person实例没问题。否则,它不是。
哦,我忘记了。在编组之前,请记住 setSchema()
SchemaFactory sf = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI);
Schema schema = sf.newSchema(new File("your.xsd"));
marshaller.setSchema(schema);
marshaller.setEventHandler(new ValidationEventHandler() {
public boolean handleEvent(ValidationEvent event) {
System.out.println(event);
return false; //to stop the marshal if anything happened
}
});
我有一个应用程序,其中我从 xsd 模式生成了 Java classes。我还有一个使用 jax-rs 的休息服务。我需要验证 POST 方法的输入,以确保符合 xsd 模式中设置的规则。
@POST
@Path("/person/add")
public void addPerson(Person person) {
//Need to validate Person object
daoManager.addPersonToDB(person);
}
Person 对象是从 xsd 生成的 class。我可以假设该对象符合 xsd,还是我必须验证该对象?在那种情况下,我该如何验证?
我知道这是一个新手问题,但我希望有人能提供帮助。
我自己还没有尝试过,但我认为下面的代码会起作用。
JAXBContext context = JAXBContext.newInstance(Person.class);
Marshaller marshaller = context.createMarshaller();
根据你的命名空间,使用
marshaller.setProperty(Marshaller.JAXB_NO_NAMESPACE_SCHEMA_LOCATION, "yourXSD.xsd");
或
marshaller.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, "yourXSD.xsd");
然后编组person实例,如果没有异常,说明person实例没问题。否则,它不是。
哦,我忘记了。在编组之前,请记住 setSchema()
SchemaFactory sf = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI);
Schema schema = sf.newSchema(new File("your.xsd"));
marshaller.setSchema(schema);
marshaller.setEventHandler(new ValidationEventHandler() {
public boolean handleEvent(ValidationEvent event) {
System.out.println(event);
return false; //to stop the marshal if anything happened
}
});