@ResponseBody用法

作用:

  • 该注解用于将Controller的方法返回的对象,根据HTTP Request Header的Accept的内容,通过适当的HttpMessageConverter转换为指定格式后,写入到Response对象的body数据区。

使用时机:

  • 返回的数据不是html标签的页面,而是其他某种格式的数据时(如json、xml等)使用.

配置返回JSON和XML数据

  • 添加jackson依赖
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.8.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.1</version>
</dependency>
  • 开启<mvc:annotation-driven />

  • java代码为

 @RequestMapping("/testResponseBody")
public @ResponseBody
Person testResponseBody() {
Person p = new Person();
p.setName("xiaohong");
p.setAge(12);
return p;
}

Person类

@XmlRootElement(name = "Person")
public class Person {
private String name;
private int age;
public String getName() { return name; }
@XmlElement
public void setName(String name) { this.name = name; }
public int getAge() { return age; }
@XmlElement
public void setAge(int age) { this.age = age; }
}
  • Ajax代码
$.ajax({
url: "testResponseBody",
type: 'GET',
headers: {
Accept: "application/xml",
// Accept:"application/json",
},
success: function(data, textStatus){
console.log(data);
alert(data);
},
error: function (data, textStatus, errorThrown) {
console.log(data);
},
});

分析

  • 如果没有配置Person类的XML注解,那么只会JSON数据,无论Accept是什么,

  • 如果配置了Person类的xml注解,那么如果Accept含有applicatin/xml, 就会返回xml数据.例如通过浏览器直接访问,浏览器的http request header appect字段一般都为
    Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8, 故返回XML数据.
    accept: "application/json",即可返回JSON数据.

用此注解或者ResponseEntity等类似类, 会导致response header含有accept-charset这个字段,而这个字段对于响应头是没有用的,以下方法可以关掉

<mvc:annotation-driven>
<mvc:async-support default-timeout="3000"/>
<!-- utf-8编码 -->
<mvc:message-converters register-defaults="true">
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<constructor-arg value="UTF-8"/>
<property name="writeAcceptCharset" value="false"/>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>

@RequestBody使用

作用:

  • 注解用于将Controller的方法参数,根据HTTP Request Header的content-Type的内容,通过适当的HttpMessageConverter转换为JAVA类

使用时机:

  • POST或者PUT的数据是JSON格式或者XML格式,而不是普通的键值对形式.

如何使用

其他代码同上, 配置Controller,如下:

@RequestMapping(value = "/testRequestBody", method= RequestMethod.POST)
@ResponseBody
public Person testRequestBody(@RequestBody Person p) {
System.out.println("creating a employee:" + p);
return p;
}

Ajax代码如下:

 $.ajax({
url: "testRequestBody",
data: '{"name":"小红","age":12}', //要用双引号!!
contentType: "application/json;charset=utf-8", // 因为上面是JSON数据 type: "POST",
headers: {
// Accept: "application/xml",
Accept: "application/json",
},
success: function(data, textStatus){
console.log(data);
alert(data);
},
error: function (data, textStatus, errorThrown) {
console.log(data);
},
});

xml类似.

总结

推荐阅读

解析Spring中的ResponseBody和RequestBody

SpringMVC @ResponseBody和@RequestBody使用的更多相关文章

  1. springMvc注解之@ResponseBody和@RequestBody

    简介 springmvc对json的前后台传输做了很好封装,避免了重复编码的过程,下面来看看常用的@ResponseBody和@RequestBody注解 添加依赖 springmvc对json的处理 ...

  2. SpringMVC 之 @ResponseBody 和 @RequestBody

    前后端进行数据交互的时候,规定数据交互的格式,使数据交互规范而统一,是极为重要的事.一般而言,我们会采用 JSON 进行数据交互.本文暂不讨论如何 JSON 的格式规范,而是解析一下如何在 Sprin ...

  3. 转-Spring 注解学习手札(七) 补遗——@ResponseBody,@RequestBody,@PathVariable

    转-http://snowolf.iteye.com/blog/1628861/ Spring 注解学习手札(七) 补遗——@ResponseBody,@RequestBody,@PathVariab ...

  4. SpringMVC @ResponseBody 415错误处理

    在查看下面部分内容之前,请先检查你的请求蚕食是否正确,如果全部正确,请继续往下看 刚开始用SpringMVC, 页面要使用jQuery的ajax请求Controller. 但总是失败,主要表现为以下两 ...

  5. Spring 注解学习手札(七) 补遗——@ResponseBody,@RequestBody,@PathVariable (转)

    最近需要做些接口服务,服务协议定为JSON,为了整合在Spring中,一开始确实费了很大的劲,经朋友提醒才发现,SpringMVC已经强悍到如此地步,佩服! 相关参考: Spring 注解学习手札(一 ...

  6. Spring 注解学习手札(七) 补遗——@ResponseBody,@RequestBody,@PathVariable(转)

    最近需要做些接口服务,服务协议定为JSON,为了整合在Spring中,一开始确实费了很大的劲,经朋友提醒才发现,SpringMVC已经强悍到如此地步,佩服! 相关参考: Spring 注解学习手札(一 ...

  7. @ResponseBody,@RequestBody,@PathVariable

    最近需要做些接口服务,服务协议定为JSON,为了整合在Spring中,一开始确实费了很大的劲,经朋友提醒才发现,SpringMVC已经强悍到如此地步,佩服! 相关参考: Spring 注解学习手札(一 ...

  8. @Responsebody与@RequestBody

    前台发送请求后台用什么接收-->@RequsetMapping 何时使用@ResponseBody-->一般在异步获取数据时使用,后台传的数据切成ison传给前台 @Responsebod ...

  9. 浅谈@RequestMapping @ResponseBody 和 @RequestBody 注解的用法与区别

    浅谈@RequestMapping @ResponseBody 和 @RequestBody 注解的用法与区别 Spring 2.5 版本新增了注解功能, 通过注解,代码编写简化了很多:但熟悉注解的使 ...

随机推荐

  1. HDU 1241.Oil Deposits-求连通块DFS or BFS

    Oil Deposits Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)Tota ...

  2. TopCoder SRM 682 Div1 Problem 450 SuccessfulMerger (环套树 + 分类讨论)

    题意  给定一个$n$个点$n$条边的无向图,现在要把这个图进行若干次操作,并选择一个点作为首都. 要求除首都外的任意两个点$u$, $v$,从$u$走到$v$必须经过这个首都. 操作为合并两个相邻的 ...

  3. Codeforces 815 C Karen and Supermarket

    On the way home, Karen decided to stop by the supermarket to buy some groceries. She needs to buy a ...

  4. GCJ——Minimum Scalar Product(2008 Round1 AA)

    题意: 给定两组各n个数,可任意调整同一组数之中数字的顺序,求 sum xi*yi i=1..n的最小值. Small: n<=8 abs xy,yi<=1000 Large: n< ...

  5. SQLServer出现不允许保存更改的问题解决

    如图所示: 解决方法: [工具]->[选项]

  6. [LeetCode] 1.Two Sum 两数之和分析以及实现 (golang)

    题目描述: /* Given an array of integers, return indices of the two numbers such that they add up to a sp ...

  7. 审查php.ini自动分析程序

    源码 https://github.com/sektioneins/pcc 使用方法 环境: mac cli 命令行执行 git clone https://github.com/sektionein ...

  8. weblogic的集群与配置图文方法

      一.Weblogic的集群 还记得我们在第五天教程中讲到的关于Tomcat的集群吗? 两个tomcat做node即tomcat1, tomcat2,使用Apache HttpServer做请求派发 ...

  9. ElasticSearch搜索term和terms的区别

    今天同事使用ES查询印地语的文章.发现查询报错,查询语句和错误信息如下: 查询语句:{    "query":{        "bool":{         ...

  10. Leetcode 编程训练(转载)

    Leetcode这个网站上的题都是一些经典的公司用来面试应聘者的面试题,很多人通过刷这些题来应聘一些喜欢面试算法的公司,比如:Google.微软.Facebook.Amazon之类的这些公司,基本上是 ...