在 Spring REST 控制器中使用 RequestBody 的 XML/JSON POST
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8339137/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
XML/JSON POST with RequestBody in Spring REST Controller
提问by Arun Kumar
I am creating a RESTful website with Spring 3.0. I am using ContentNegotiatingViewResolveras well as HTTP Message Convertors (like MappingHymansonHttpMessageConverterfor JSON, MarshallingHttpMessageConverterfor 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.
我正在使用 Spring 3.0 创建一个 RESTful 网站。我正在使用ContentNegotiatingViewResolver以及 HTTP 消息转换器(如MappingHymansonHttpMessageConverter用于 JSON、MarshallingHttpMessageConverter用于 XML 等)。如果我在 url 的最后一个使用 .xml 后缀,并且在 URL 中使用 .json 后缀的 JSON 的情况下,我能够成功获取 XML 内容。
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?
从控制器获取 XML/JSON 内容对我来说没有任何问题。但是,如何在同一个 Controller 方法中使用请求正文发布 XML/JSON?
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);
}
回答by stoffer
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 MappingHymansonHttpMessageConverter will automatic translate your Employee Object to JSON if you use a method definition and implementation like this (note, not tested):
您应该考虑不使用 View 来返回 JSON(或 XML),而是使用 @ResponseBody 注释。如果应该返回的是员工,那么如果您使用这样的方法定义和实现(注意,未测试),Spring 和 MappingHymansonHttpMessageConverter 将自动将您的员工对象转换为 JSON:
@RequestMapping(method=RequestMethod.POST, value="/addEmployee")
@ResponseBody
public Employee addEmployee(@RequestBody Employee e) {
Employee created = employeeDao.add(e);
return created;
}

