Kamaldeep Verma
Kamaldeep Verma

Reputation: 11

How to unmarshall xml from Http Post Rest Web Service with Jaxb using spring mvc?

My Spring MVC Web Service code is as follows.

Model Class

@XmlRootElement(name="secretData")
public class VData {


        private long lKId;



        @XmlElement(name="kId")
        public long getlKId() {
            return lKId;
        }


        public void setlKId(long lKId) {
            this.lKId = lKId;
        }       
    }

Controller Method

@RequestMapping(value = "/vendor", method = RequestMethod.POST)
        public String addVendor(@RequestBody VData vData) {

            /*Checking recieved value*/
            System.out.println(vData.getlKId());//**Returning 0 value **
            return "Success";
        }

Xml request body for web service

<secretData>
    <kId>1</kId>
</secretData>

I am getting "0" value in lKId. Where am I doing wrong. Please provide the correct way to bind the xml element to object member using @XmlElement(name="kId") annotation.

Upvotes: 1

Views: 1607

Answers (3)

Nadeem Qureshi
Nadeem Qureshi

Reputation: 11

You have to add @XmlElement annotation on setter and not on getter. @XmlAttribute annotation has to be put on getter.

Upvotes: 0

Stefaan Neyts
Stefaan Neyts

Reputation: 2092

To enable OXM (object to XML mapping) in Spring Web MVC, Spring needs a HttpMessageConverter which can read/write from/to XML. There are several implementations available in Spring using Jackson, XStream, JAXB, ...

Spring should automatically adds a HttpMessageConverter when it detects one of these libraries in the classpath. Do you have the JAXB library on the classpath?

You can also manually register the Jaxb2RootElementHttpMessageConverter as a bean. Through JavaConfig this looks like:

@Bean
public HttpMessageConverter oxmHttpMessageConverter() {
return new Jaxb2RootElementHttpMessageConverter();
}

Upvotes: 3

Monzurul Shimul
Monzurul Shimul

Reputation: 8396

Add consumes = MediaType.APPLICATION_XML_VALUE inside your @RequestMapping to tell controller that this method will consume xml only.

    @RequestMapping(value = "/vendor", method = RequestMethod.POST, consumes = MediaType.APPLICATION_XML_VALUE) 
    public String addVendor(@RequestBody VData vData) {
        /*Checking recieved value*/ 
        System.out.println(vData.getlKId());//**Returning 0 value **
        return "Success"; 
    } 

And while you are posting xml through http, set header Content-type:application/xml

Upvotes: 0

Related Questions