SpringBoot通过JSON传递请求参数的实例详解

作者:IT利刃出鞘 时间:2023-11-26 22:59:24 

简介

本文用示例介绍SpringMVC如何通过JSON格式传递入参。

JSON格式使用post方式来请求,即:对应的注解为:@PostMapping。

@PostMapping注解的方法可以接收1个@RequestBody标记的参数和多个没有@RequestBody标记的参数

代码

Entity

User.java

package com.example.demo.entity;

import lombok.Data;
import java.util.List;

@Data
public class User {
   private String name;
   private Integer age;
   private String[] password;
   private List<Integer> scoreArray;
}

Account.java

package com.example.demo.entity;

import lombok.Data;
import java.io.Serializable;

@Data
public class Account implements Serializable {
   private String phoneNum;
   private String[] emails;
}

Controller

package com.example.demo.controller;

import com.example.demo.entity.User;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Arrays;
import java.util.List;

@RequestMapping("/json")
@RestController
public class JsonController {
   @PostMapping("/1")
   public User setUserNoAnnotation(User user, List<String> password, Integer[] scoreArray) {
       printUser(user);
       return user;
   }

@RequestMapping("/2")
   public User setUserAnnotation(@RequestBody User user) {
       printUser(user);
       return user;
   }

@RequestMapping("/3")
   public User setUserAnnotation1(@RequestBody User user, @RequestParam List<String> password, Integer[] scoreArray) {
       System.out.println(password);
       if (scoreArray != null) {
           System.out.println(Arrays.asList(scoreArray));
       } else {
           System.out.println("scoreArray = null");
       }
       System.out.println();
       printUser(user);

return user;
   }

@RequestMapping("/4")
   public User setUserAnnotation2(@RequestBody User user, @RequestBody List<String> password, @RequestBody Integer[] scoreArray) {
       if (password != null) {
           System.out.println(password);
       } else {
           System.out.println("password = null");
       }

if (scoreArray != null) {
           System.out.println(Arrays.asList(scoreArray));
       } else {
           System.out.println("scoreArray = null");
       }
       System.out.println();
       printUser(user);
       return user;
   }

private void printUser(User user){
       System.out.println("name            : " + user.getName());
       System.out.println("password        : " + Arrays.asList(user.getPassword()));
       System.out.println("scoreArray      : " + user.getScoreArray());
       System.out.println("acount.phoneNum : " + user.getAccount().getPhoneNum());
       System.out.println("account.emails  : " + Arrays.asList(user.getAccount().getEmails()));
   }
}

测试

为方便测试,我用了knife4j。

测试前提

json的body

{
   "name": "Jarvis",
   "password": [
       "ab",
       "cd"
   ],
   "scoreArray": [
       99,
       98
   ],
   "account": {
       "phoneNum": "123",
       "emails": [
           "123@qq.com",
           "456@163.com"
       ]
   }
}

正确的用法

1个RequestBody

SpringBoot通过JSON传递请求参数的实例详解

0个@RequestBody,多个无@RequestBody

SpringBoot通过JSON传递请求参数的实例详解

1个@RequestBody,多个无@RequestBody

SpringBoot通过JSON传递请求参数的实例详解

错误的用法(会报错)

多个@RequestBody

SpringBoot通过JSON传递请求参数的实例详解

后端报错信息

2022-09-20 22:04:45.857  WARN 3340 --- [nio-8080-exec-1] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotReadableException: I/O error while reading input message; nested exception is java.io.IOException: Stream closed]

错误原因

每个方法只能有一个@RequestBody。使用@RequestBody把请求转化为特定的Object(在最后会关闭相应的流),所以在同一个方法中第二次使用@RequestBody是没用的,因为流已经关闭。

You cannot use it this way as only one @RequestBody per method is allowed. Using @RequestBody Spring converts incoming request body into the specified object (what closes the stream representing body at the end) so attempting to use @RequestBody second time in the same method makes no sense as stream has been already closed.

不带@RequestBody参数类型是List

SpringBoot通过JSON传递请求参数的实例详解

后端错误信息

2022-09-20 23:19:11.044 ERROR 3340 --- [nio-8080-exec-2] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.IllegalStateException: No primary or default constructor found for interface java.util.List] with root cause
java.lang.NoSuchMethodException: java.util.List.<init>()
    at java.lang.Class.getConstructor0(Class.java:3082) ~[na:1.8.0_201]
    at java.lang.Class.getDeclaredConstructor(Class.java:2178) ~[na:1.8.0_201]
    ...(其他信息)

错误原因

不支持非@RequstBody的参数是List类型。(数组类型可以)。

来源:https://blog.csdn.net/feiying0canglang/article/details/126955477

标签:springboot,json,参数
0
投稿

猜你喜欢

  • Unity shader实现百叶窗特效

    2023-06-05 00:05:49
  • android学习笔记之View的滑动

    2022-12-30 07:51:36
  • SpringCloud服务实现同时使用eureka和nacos方法

    2022-01-14 13:58:57
  • Unity实现答题系统的示例代码

    2022-05-09 18:31:00
  • C#不提升自己程序的权限实现操作注册表

    2023-01-24 18:51:31
  • 谈谈变量命名规范的重要性

    2021-08-10 22:40:13
  • C# WinForm程序完全退出的问题解决

    2023-07-02 07:29:34
  • Android使用AudioManager修改系统音量的方法

    2023-11-20 09:10:00
  • 基于swing实现窗体拖拽和拉伸

    2023-11-12 22:32:40
  • C#适配器模式的使用

    2022-02-05 15:47:21
  • C# WinForm快捷键设置技巧

    2023-07-20 07:03:13
  • java使用正则抓取网页邮箱

    2022-12-02 10:30:30
  • 七个Spring核心模块详解

    2021-07-25 15:32:18
  • C# javascript 读写Cookie的方法

    2023-03-19 08:03:16
  • springmvc用于方法鉴权的注解拦截器的解决方案代码

    2022-06-02 10:30:18
  • IOS开发向右滑动返回前一个页面功能(demo)

    2021-09-23 04:30:11
  • C#中异步回调函数用法实例

    2023-01-05 13:10:53
  • 基于SpringBoot实现用户身份验证工具

    2022-05-08 18:37:29
  • Java的Spring框架下的AOP编程模式示例

    2023-11-02 00:52:25
  • C#中委托的基础入门与实现方法

    2022-05-24 22:04:24
  • asp之家 软件编程 m.aspxhome.com