当前位置: 首页 > news >正文

java接口 controller层接收list集合传参,postman 调用接口时required parameter XXX is not present

开发过程中开发一个java接口 controller层接收list集合传参,然后postman调用一直不成功,报错

使用@RequestParam方式,如果postman 调用接口时报错required parameter XXX is not present
可能是(value=“items”)跟你输入参数时的key——items输入不一致,去掉(value=“items”)或者检查输入一样的值可解决此问题,详情可看下面的@RequestParam方式

一:java后端接口写法

下面是一个简单的例子,展示如何在Spring MVC的Controller中接收一个List类型的参数。

一,使用@RequestBody传参

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;import java.util.List;@RestController
public class MyController {@PostMapping("/processList")public String processList(@RequestBody List<String> items) {// 这里处理接收到的列表for (String item : items) {System.out.println("Received: " + item);}return "List processed successfully.";}
}
1,在这个例子中:

@RestController 注解表示这是一个RESTful风格的控制器。
@PostMapping(“/processList”) 表明该方法将处理发送到/processList路径的POST请求。
@RequestBody 注解告诉Spring框架将请求体中的内容转换为相应的Java类型,在这里是List类型。
客户端可以发送类似以下格式的JSON数据:

当客户端发送POST请求到/processList端点时,Spring会自动将请求体中的JSON数组转换成List对象,并将其传递给processList方法进行处理。

如果列表中的元素是复杂的对象而不是简单的字符串,您可以将String替换为您自己的类名,例如List,并且确保客户端发送的JSON数据与您的类结构相匹配。

2,使用postman请求,

设置请求头
点击“Headers”选项卡,添加一个新的键值对来指定Content-Type为application/json,这告诉服务器你发送的数据是JSON格式。

keyvalue
Content-Typeapplication/json

如下图:(Cookie设置是因为我的服务需要登录验证)
在这里插入图片描述

请求接口:
点击“Body”选项卡,并选择“raw”作为输入类型,然后选择“JSON (application/json)”作为子选项。在文本框中输入你要发送的JSON数据。
在这里插入图片描述

二,@RequestParam方式

1使用查询参数 (Query Parameters)

如果列表数据不是很大,可以考虑使用查询参数的方式发送。但是请注意,这种方法通常不适用于较大的列表数据。

在Postman中设置
请求类型:POST
URL:http://localhost:8080/processList
查询参数:在URL后面添加查询参数,例如:

http://localhost:8080/processList?items=item1&items=item2&items=item3

后端代码示例

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;@RestController
public class MyController {@GetMapping("/processList")public String processList(@RequestParam (value="items"List<String> items) {for (String item : items) {System.out.println("Received: " + item);}return "List processed successfully.";}
}
2. 使用表单数据 (Form Data)

可以使用表单数据的方式发送列表中的每一项作为一个单独的表单字段。
请求的时候 选择form-data选项,为每个列表项添加一个键值对:
键:items (多次添加,每次的值不同)
值:列表项的值:

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;@RestController
public class MyController {@PostMapping("/processList")public String processList(@RequestParam List<String> items) {for (String item : items) {System.out.println("Received: " + item);}return "List processed successfully.";}
}

在这里插入图片描述

三,使用自定义对象

public class ItemList {private List<String> items;// Getter and Setterpublic List<String> getItems() {return items;}public void setItems(List<String> items) {this.items = items;}
}

在Postman中设置
请求类型:POST
URL:http://localhost:8080/processList
Body:选择raw,并选择JSON (application/json),然后输入:

{"items": ["item1", "item2", "item3"]
}

后端代码示例

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;import java.util.List;@RestController
public class MyController {@PostMapping("/processList")public String processList(@RequestBody ItemList itemList) {List<String> items = itemList.getItems();for (String item : items) {System.out.println("Received: " + item);}return "List processed successfully.";}
}

这些方法都可以根据实际需求选择使用。如果你的数据量较大或者数据格式比较复杂,推荐使用JSON对象的方式。而对于较小的数据集,可以考虑使用查询参数或表单数据。

二:java后端接口写法

使用JSP页面结合jQuery和Ajax来调用后端接口,下面是四种方法,对应后端几种调用方式

1. 使用JSON数组

这是最直接的方式,适合于发送JSON格式的数据。

HTML/JSP 页面

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Ajax Example</title><script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body><button id="sendData">Send Data</button><script>$(document).ready(function () {$('#sendData').click(function () {var data = ['item1', 'item2', 'item3'];$.ajax({url: 'http://localhost:8080/processList',type: 'POST',contentType: 'application/json',data: JSON.stringify(data),success: function (response) {console.log('Success:', response);},error: function (error) {console.error('Error:', error);}});});});</script>
</body>
</html>

2. 使用查询参数

如果列表数据不是很大,可以通过查询参数发送。

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Ajax Example</title><script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body><button id="sendData">Send Data</button><script>$(document).ready(function () {$('#sendData').click(function () {var data = ['item1', 'item2', 'item3'];var query = data.map(item => `items=${encodeURIComponent(item)}`).join('&');$.ajax({url: `http://localhost:8080/processList?${query}`,type: 'GET',success: function (response) {console.log('Success:', response);},error: function (error) {console.error('Error:', error);}});});});</script>
</body>
</html>

3. 使用表单数据

可以模拟发送表单数据的方式发送列表数据。

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Ajax Example</title><script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body><button id="sendData">Send Data</button><script>$(document).ready(function () {$('#sendData').click(function () {var data = ['item1', 'item2', 'item3'];var formData = new FormData();data.forEach(item => {formData.append('items', item);});$.ajax({url: 'http://localhost:8080/processList',type: 'POST',data: formData,processData: false, // 不要让jQuery处理数据contentType: false, // 不要设置content-type请求头success: function (response) {console.log('Success:', response);},error: function (error) {console.error('Error:', error);}});});});</script>
</body>
</html>

4, 使用自定义对象

定义一个包含列表属性的对象,并发送整个对象。

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Ajax Example</title><script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body><button id="sendData">Send Data</button><script>$(document).ready(function () {$('#sendData').click(function () {var data = {items: ['item1', 'item2', 'item3']};$.ajax({url: 'http://localhost:8080/processList',type: 'POST',contentType: 'application/json',data: JSON.stringify(data),success: function (response) {console.log('Success:', response);},error: function (error) {console.error('Error:', error);}});});});</script>
</body>
</html>

http://www.mrgr.cn/news/9261.html

相关文章:

  • 苍穹外卖项目DAY01
  • 数学建模学习(125):使用Python实现灰色关联分析从理论到实战
  • Python习题 146:用lambda和filter函数返回偶数
  • 数据采集-->kafka-->hdfs
  • 自动化与高效设计:推理技术在FPGA中的应用
  • Obsidian Publish的开源替代品Markopolis
  • [数据集][目标检测]管道漏水泄漏破损检测数据集VOC+YOLO格式2614张4类
  • 《深度学习》 OpenCV 计算机视觉入门 (中篇)
  • 解决WIndows10下更新蓝牙驱动屡屡失败问题
  • C/C++语言基础--结构体知识详解(包括:结构体数组、字节对齐、位段等内容)
  • Git 的配置
  • find 命令
  • WEB渗透Win提权篇-RDPFirewall
  • 79、ansible-----playbook2
  • MacOS如何升级ruby版本?
  • GDB的使用(3)
  • Spring Boot整合MyBatis-Plus的详细讲解
  • uniapp h5手机如何打开本地跑的前端项目进行本地调试
  • (十八)Flink CEP 详解
  • 视频在线去水印解析相册怎么弄,轻松掌握五大技巧