我正在用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
发布评论