09-请求与参数处理-参数-JSON类型

新建com.example.controller.JsonController

package com.example.controller;

import com.example.pojo.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author Administrator
 */
@Controller
public class JsonController {
    @RequestMapping("/json")
    @ResponseBody
    public String json(@RequestBody User user) {
        System.out.println(user);
        return "json";
    }
}

启动测试

后端控制台打印

[WARNING] Resolved [org.springframework.http.converter.HttpMessageNotReadableException: Required request body is missing: public java.lang.String com.example.controller.JsonController.json(com.example.pojo.User)]

 pom.xml文件添加依赖

<dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.15.3</version>
    </dependency>

启动测试

后端打印

User(name=zhangsan, age=12)

 注释掉SpringMvcConfig的@EnableWebMvc注解

//@EnableWebMvc//开启SpringMVC的辅助功能,其中就包括字符串转成日期格式的数据、json数据格式的自动转换

启动测试

后端打印

[WARNING] Resolved [org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/json' not supported]

 在JsonController中添加代码

 @RequestMapping("/jsonList")
    @ResponseBody
    public String jsonList(@RequestBody List<String> list){
        System.out.println(list);
        return "jsonList";
    }

打开SpringMvcConfig中@EnableWebMvc注解

启动测试

后端打印

[a, b, c]

 修改jsonList方法

 public String jsonList(@RequestBody String[] list) {
        System.out.println(Arrays.toString(list));
        return "jsonList";
    }

启动测试

后端打印

[a, b, c]

 添加代码

  @RequestMapping("/pojoArrayParamForJson")
    @ResponseBody
    public String jsonList2(@RequestBody List<User> list) {
        System.out.println(list);
        return "pojoArrayParamForJson";
    }

启动测试

后端打印

[User(name=zhangsan, age=12), User(name=zhangsan, age=12)]

 请求参数(传递json数据)

名称:@RequestBody

类型:形参注解

位置:SpringMVC控制器方法形参定义前面

作用:将请求中请求体所包含的数据传递给请求参数,此注解一个处理器方法只能使用一次

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

敲代码的翠花

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值