@ResponseBody与@RequestBody注解的用法

  • Post author:
  • Post category:其他


记录一下这两个注解最基本的用法,作为复习



@ResponseBody

作用:@ResponseBody注解用于将Controller的方法返回的对象,通过springmvc提供的

HttpMessageConverter

接口转换为指定格式的数据如:json,xml等,通过Response响应给客户端。



@RequestBody

作用:@RequestBody注解用于读取http请求的内容(

字符串

),通过springmvc提供的HttpMessageConverter接口将读到的内容(json数据)转换为java对象并绑定到Controller方法的参数上。



什么是HttpMessageConverter

作用:负责将请求信息转换为一个对象(类型为 T),将对象(类型为 T)输出为响应信息。

在这里插入图片描述



代码测试:

(1)搭建SpringMVC的web开发环境(可以参照我上一篇博客

纯注解搭建springmvc环境



注意:要使用这两个注解,就一定要有jackson的相关jar包

   <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.8</version>
        </dependency>

导入了jar包之后,如果配置了

<mvc:annotation-driven />

或者使用了注解

@EnableWebMvc

,那么容器在启动的时候就会自动装载json的

HttpMessageConverter

如下图所示:

在这里插入图片描述

<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2019/6/14
  Time: 18:48
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <script type="text/javascript" src="/js/jquery-1.5.1.min.js"></script>
    <title>Title</title>
    <script>
        $(function () {
            $("button[name='butt1']").click(function () {
                $.ajax({
                    url: "/save",
                    data:JSON.stringify({"userName":"张三","age":"18"}),
                    type: "POST",
                    success: function (data) {
                        alert(data);
                    },
                    contentType: "application/json;charset=utf-8"
                });
            });
        })
    </script>
</head>
<body>
<button name="butt1">提价post</button>
</body>
</html>

点击提交,发送post请求,提价json字符串数据,需要指定

contentType: "application/json;charset=utf-8"

不然会报

415

错误

这里说明一下json字符串和json对象时两个不同的概念:

var user ={“userName”:“张三”,“age”:“18”} 这里user 是一个json对象,类型是object 可以通过user.name和user.age取到对应的值

var user1= ‘{“userName”:“张三”,“age”:“18”}’ 这里user1 就是一个字符串,是符合{k:v,k:v}这种json格式的字符串而已,不能通过上面那种方式取值。

可以通过一定的方法相互转换:json对象转json字符串 1、可以直接单引号 2、通过JSON.stringify(xxx)

json字符串转json对象:JSON.parse(xxxx)


controller层代码

    @PostMapping("/save")
    @ResponseBody
    public User save(@RequestBody  User user){
    //将前台传过来的数据 以json的格式相应回浏览器
        return user ;
    }
}

开始测试:

在这里插入图片描述

打开控制台:点击提价之后

在这里插入图片描述

可以发现请求体就是data的内容信息。

contentType

也就是设置的

application/json;charset=utf-8

,然后再查看一下相应信息

在这里插入图片描述

user对象特定的json格式,响应给了浏览器。


总结:


我们前台请求过去的json字符串,在使用@RequestBody注解后 被HttpMessageConverter,转换成对应的java对象,然后我们在用@ResponseBody注解,将java对象 以特定的格式(通常都是json)相应给浏览器。



版权声明:本文为weixin_43732955原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。