【问题标题】:Validate object against xsd / generated object针对 xsd / 生成的对象验证对象
【发布时间】:2016-03-31 08:17:02
【问题描述】:

我有一个从 xsd 模式生成 Java 类的应用程序。我也有使用 jax-rs 的休息服务。我需要验证 POST 方法的输入,以确保符合 xsd 架构中设置的规则。

@POST
@Path("/person/add")
public void addPerson(Person person) {

    //Need to validate Person object 

    daoManager.addPersonToDB(person);
}

Person 对象是从 xsd 生成的一个类。我可以假设该对象符合 xsd,还是必须验证该对象?那么,我该如何验证?

我知道这是一个新手问题,但我希望有人能提供帮助。

【问题讨论】:

    标签: java validation xsd jaxb jax-rs


    【解决方案1】:

    我自己没有试过,但我认为下面的代码可以工作。

    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
          }
        });
    

    【讨论】:

    猜你喜欢
    • 2012-09-26
    • 2011-10-15
    • 2017-08-14
    • 1970-01-01
    • 1970-01-01
    • 2013-04-22
    • 1970-01-01
    • 1970-01-01
    • 2013-12-22
    相关资源
    最近更新 更多