XML/JSON POST with RequestBody in Spring REST Controller

一世执手 提交于 2019-12-09 13:13:23

问题


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);
}

回答1:


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;
   }


来源:https://stackoverflow.com/questions/8339137/xml-json-post-with-requestbody-in-spring-rest-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!