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

23 篇文章 0 订阅

开发过程中开发一个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 Setter
    public 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>
  • 18
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

见未见过的风景

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

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

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

打赏作者

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

抵扣说明:

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

余额充值