Spring REST Controller中带有RequestBody的XML/JSON POST

编程入门 行业动态 更新时间:2024-10-12 05:45:29
本文介绍了Spring REST Controller中带有RequestBody的XML/JSON POST的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在用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

本文发布于:2023-11-24 22:11:13,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1627061.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Controller   REST   Spring   RequestBody   POST

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!