2016-03-31 83 views
2

我有一個應用程序,我從xsd模式生成Java類。我也有使用jax-rs的休息服務。我需要驗證POST方法的輸入,以確保符合xsd模式中設置的規則。驗證對象xsd /生成的對象

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

    //Need to validate Person object 

    daoManager.addPersonToDB(person); 
} 

Person對象是從xsd生成的類。我可以假定對象符合xsd,還是必須驗證對象?在那種情況下,我如何驗證?

我知道這是一個新手問題,但我希望有人可以提供幫助。

回答

2

我還沒有嘗試過自己,但我認爲下面的代碼將工作。

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

,然後當元帥的人來說,如果沒有異常,這意味着人的實例是罰款。否則,它不是。


哦,我忘了東西。在編組之前,請記住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 
     } 
    }); 
+0

還有另一篇文章可能會對您有所幫助。 http://www.java2s.com/Code/Java/XML/UseMarshalValidation.htm –