该注解用于将 Controller 的方法返回的对象,通过 HttpMessageConverter 接口转换为指定格式的数据如:json,xml 等,通过 Response 响应给客户端
示例
需求:使用@ResponseBody 注解实现将 controller 方法返回对象转换为 json 响应给客户端。
前置知识点:Springmvc 默认用 MappingJacksonHttpMessageConverter 对json数据进行转换,需要加入jackson 的包。
注:2.7.0以下的版本用不了
jsp代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | <!-- 测试异步请求 --> <input type= "button" value= "测试ajax请求json和响应json" id= "testJson" /> <script type= "text/javascript" src= "${pageContext.request.contextPath}/js/jquery.min.js" ></script> <script type= "text/javascript" > $( function (){ $( "#testJson" ).click( function (){ $.ajax({ type: "post" , url: "${pageContext.request.contextPath}/testResponseJson" , contentType: "application/json;charset=utf-8" , data:JSON.stringify({ "id" :1, "name" : "test" , "money" :999.0}), dataType: "json" , success: function (data){ alert(data); } }); }); }) </script> |
控制器代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | /** * 响应 json 数据的控制器 * @author 黑马程序员 * @Company http://www.ithiema.com * @Version 1.0 */ @Controller ( "jsonController" ) public class JsonController { /** * 测试响应 json 数据 */ @RequestMapping ( "/testResponseJson" ) public @ResponseBody Account testResponseJson( @RequestBody Account account) { System.out.println( "异步请求:" +account); return account; } } |
配置json转换器
如果不使用注解驱动<mvc:annotation-driven />,就需要给处理器适配器配置json转换器
在springmvc.xml配置文件中,给处理器适配器加入json转换器:
1 2 3 4 5 6 7 8 | <!--处理器适配器 --> < bean class = "org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter" > < property name = "messageConverters" > < list > < bean class = "org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" ></ bean > </ list > </ property > </ bean > |
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持自学编程网。
- 本文固定链接: https://zxbcw.cn/post/198226/
- 转载请注明:必须在正文中标注并保留原文链接
- QQ群: PHP高手阵营官方总群(344148542)
- QQ群: Yii2.0开发(304864863)