Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XML/JSON POST with RequestBody in Spring REST Controller

I am creating a RESTful website with Spring 3.0. I am using ContentNegotiatingViewResolver as well as HTTP Message Convertors (like MappingJacksonHttpMessageConverter for JSON, MarshallingHttpMessageConverter for XML, etc.). I am able to get the XML content successfully, if I use the .xml suffix in the last of url and same in case of JSON with .json suffix in URL.

Getting XML/JSON contents from controller doesn't produce any problem for me. But, how can I POST the XML/JSON with request body in same Controller method?

For e.g.

@RequestMapping(method=RequestMethod.POST, value="/addEmployee")
   public ModelAndView addEmployee(@RequestBody Employee e) {
        employeeDao.add(e);
        return new ModelAndView(XML_VIEW_NAME, "object", e);
}
like image 651
Arun Kumar Avatar asked Dec 01 '11 09:12

Arun Kumar


People also ask

Is @RequestBody required with @RestController?

Remember, we don't need to annotate the @RestController-annotated controllers with the @ResponseBody annotation since Spring does it by default.

CAN REST API use XML and JSON?

The REST architecture allows API providers to deliver data in multiple formats such as plain text, HTML, XML, YAML, and JSON, which is one of its most loved features.

What is @RequestBody in REST API?

A request body is data sent by the client to your API. A response body is the data your API sends to the client. Your API almost always has to send a response body. But clients don't necessarily need to send request bodies all the time.

What is the use of @RequestBody annotation in Spring?

The @RequestBody annotation allows us to retrieve the request's body. We can then return it as a String or deserialize it into a Plain Old Java Object (POJO). Spring has built-in mechanisms for deserializing JSON and XML objects into POJOs, which makes this task a lot easier as well.


1 Answers

You should consider not using a View for returning JSON (or XML), but use the @ResponseBody annotation. If the employee is what should be returned, Spring and the MappingJacksonHttpMessageConverter will automatic translate your Employee Object to JSON if you use a method definition and implementation like this (note, not tested):

   @RequestMapping(method=RequestMethod.POST, value="/addEmployee")
   @ResponseBody
   public Employee addEmployee(@RequestBody Employee e) {
     Employee created = employeeDao.add(e);
     return created;
   }
like image 144
stoffer Avatar answered Oct 13 '22 13:10

stoffer