SpringMVC @ResponseBody和@RequestBody使用

 
 

Springmvc进行json交互

(1)请求json、输出json,要求请求的是json串,所以在前端页面中需要将请求的内容转成json,不太方便。 (2)请求key/value、输出json。此方法比较常用。

@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格式,而不是普通的键值对形式.
  • A) GET、POST方式提时, 根据request header Content-Type的值来判断:

    •     application/x-www-form-urlencoded, 不处理(即非必须,因为这种情况的数据@RequestParam, @ModelAttribute也可以处理,当然@RequestBody也能处理);
    •     multipart/form-data, 不能处理(即使用@RequestBody不能处理这种格式的数据);
    •     application/json, application/xm, 必须(这些格式的数据,必须使用@RequestBody来处理);

    B) PUT方式提交时, 根据request header Content-Type的值来判断:

    •     application/x-www-form-urlencoded, 必须;
    •     multipart/form-data, 不能处理;
    •     其他格式, 必须;

    说明:request的body部分的数据编码格式由header部分的Content-Type指定;


该注解常用来处理Content-Type: 不是application/x-www-form-urlencoded编码的内容,而是处理例如application/json, application/xml等;它是通过使用HandlerAdapter 配置的HttpMessageConverters来解析post data body,然后绑定到相应的bean上,



如何使用

其他代码同上, 配置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



作者:tenlee
链接:https://www.jianshu.com/p/7097fea8ce3f
來源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值