Spring REST Controller中带有RequestBody的XML/JSON POST [英] XML/JSON POST with RequestBody in Spring REST Controller
问题描述
我正在用Spring 3.0创建一个RESTful网站.我正在使用ContentNegotiatingViewResolver
以及HTTP消息转换器(例如MappingJacksonHttpMessageConverter
用于JSON,MarshallingHttpMessageConverter
用于XML等).如果我在url的末尾使用.xml后缀,并且在JSON与URL带有.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内容对我来说没有任何问题.但是,如何在同一Controller方法中以请求正文发布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会自动将Employee对象转换为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 Controller中带有RequestBody的XML/JSON POST的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!