Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring XML Binding

Tags:

rest

spring

xml

I am attempting to create a RESTful service that takes incoming XML and parses the results into a business object. I have the XML and the business object.

Is there a way to perform data-binding in terms of taking the xml coming into the RESTful service and automatically creating a business object.

Currently I am doing this part manually which I am pretty sure is not the best way to do this. I am thinking maybe there is way to map xml and transfer to object. Thanks.

like image 528
Bill Lee Avatar asked Mar 27 '26 17:03

Bill Lee


1 Answers

You can accomplish this using an OXM (e.g. JAXB) and Spring Web MVC's @RequestBody annotation. Here's a simple RESTful example for creating a user object from an XML payload:

@RequestMapping(
    value = "/users",
    method = RequestMethod.POST,
    headers = "content-type=application/xml")
@ResponseStatus(HttpStatus.CREATED)
public String createUser(@RequestBody User user, HttpServletResponse res) {
    Long userId = userDao.create(user);
    response.addHeader("Location", "/users/" + userId);
    return null;
}

It sounds like you already have the XML payload part working so I'll leave it at that.