在 Spring REST 控制器中使用 RequestBody 的 XML/JSON POST [英] XML/JSON POST with RequestBody in Spring REST Controller
问题描述
我正在使用 Spring 3.0 创建一个 RESTful 网站.我正在使用 ContentNegotiatingViewResolver
以及 HTTP 消息转换器(例如用于 JSON 的 MappingJacksonHttpMessageConverter
、用于 XML 的 MarshallingHttpMessageConverter
等).如果我在 url 的最后使用 .xml 后缀,并且在 URL 中带有 .json 后缀的 JSON 的情况下,我能够成功获取 XML 内容.
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.
从控制器获取 XML/JSON 内容对我来说没有任何问题.但是,如何在同一控制器方法中发布带有请求正文的 XML/JSON?
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?
例如
@RequestMapping(method=RequestMethod.POST, value="/addEmployee")
public ModelAndView addEmployee(@RequestBody Employee e) {
employeeDao.add(e);
return new ModelAndView(XML_VIEW_NAME, "object", e);
}
推荐答案
您应该考虑不使用 View 来返回 JSON(或 XML),而是使用 @ResponseBody 注释.如果员工是应该返回的,Spring 和 MappingJacksonHttpMessageConverter 将自动将您的员工对象转换为 JSON,如果您使用这样的方法定义和实现(注意,未测试):
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;
}
这篇关于在 Spring REST 控制器中使用 RequestBody 的 XML/JSON POST的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!