How to validate the incoming invalid XML @RequestBody with the Java Bean class

I have a xml java bean class Data annotated with all the required xml annotations. Now when i try to post a xml request using postman with the correct xml format it works fine in the controller post method. But when i purposely add an extra xml tag (for testing invalid format) say <blabla></blabla> in postman and post it then again the controller does not throws any error and the code is working fine. Also the validator.validate() method also does not throws any error. I want to validate the invalid xml format against the Java Bean class.

Controller method: public DataRes ekycRequest(@RequestBody Data data)

Note – Marshalling and Unmarshalling is the later process in the controller method.

Scenario 1: There is a DTO xml bean class (Data.java) annotated with all xml annotations and has 3 fields name, age, location. Now when i try to post a xml with the correct format i.e with three xml tags it is mapped in the controller (@RequestBody Data data) and no error.

Scenario 2: But when i try to add an additional tag purposely to test invalid xml format say and post the xml request the (@RequestBody Data data) does not throws any error. I need a solution for this. It must throw error.

Scenario 3: When i try to avoid one tag and post xml with 2 tags i.e. invalid format then (@ResponseBody Data data) throws error which is what is needed in the above case i.e. scenario 2 also.

Like in Hibernate DTO bean class (annotated with @Entity) we use @Valid annotation in controller argument to validate the incoming data. In the similar manner is there similar approach wfor the xml annotated beans class.

Add Comment
1 Answer(s)

Are you setting your schema for validation when unmarshalling your Java bean? It depends on what type of validation you are using? You can also find your answer How to validate an XML against schema using JAXB? here and follow the blogpost.

Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.