XML / JSON POST with RequestBody in Spring REST Controller

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

Getting the XML / JSON content from the controller does not pose any problems for me. But, how can I POST XML / JSON with the request body in the same controller method?

For instance,

 @RequestMapping(method=RequestMethod.POST, value="/addEmployee") public ModelAndView addEmployee(@RequestBody Employee e) { employeeDao.add(e); return new ModelAndView(XML_VIEW_NAME, "object", e); } 
+6
source share
1 answer

You should not use the view to return JSON (or XML), but use the @ResponseBody annotation. If the worker is what should be returned, Spring and MappingJacksonHttpMessageConverter will automatically convert your Employee object to JSON if you use the method definition and its implementation like this (note, not verified):

  @RequestMapping(method=RequestMethod.POST, value="/addEmployee") @ResponseBody public Employee addEmployee(@RequestBody Employee e) { Employee created = employeeDao.add(e); return created; } 
+11
source

Source: https://habr.com/ru/post/902826/


All Articles