请求响应-04.请求-数组集合参数

当浏览器发起数组集合参数的请求时,服务端只需要保证controller方法中的方法形参名称与浏览器发起请求的参数名称相同即可。

一.应用场景

在html表单中,有一个表单是支持多选的,那就是checkbox复选框组件,复选框组件中的值是可以选择多个的。

多个值如何提交呢?

 多个值也将每个值正常提交即可,那么服务端如何接收呢?

接收方式也有两种:1. 数组       2.集合

二.数组接收

使用数组接收时,只需要保证数组名与请求参数名相同且请求参数为多个,定义数组类型形参即可接收参数。

package com.gjw.controller;
/**
 * 目标:掌握原始方式和springboot方式对于简单参数的请求响应
 *      掌握springboot方式对于实体参数的请求响应
        掌握springboot方式对于数组集合参数的请求响应
 */

import com.gjw.pojo.User;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

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

@RestController
public class RequestController {
    // 3.请求-数组集合参数
    @RequestMapping("/arrayParam")
    public String arrayParam(String[] hobby){
        System.out.println(Arrays.toString(hobby));
        return "OK";
    }
}

三.集合接收 

当使用集合时,需要让集合名与要传递的参数名称保持一致,并且前面加上@RequestParam修饰

package com.gjw.controller;
/**
 * 目标:掌握原始方式和springboot方式对于简单参数的请求响应
 *      掌握springboot方式对于实体参数的请求响应
 */

import com.gjw.pojo.User;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

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

@RestController
public class RequestController {
    @RequestMapping("/collectionParam")
    public String collectionParam(@RequestParam List<String> hobby){
        System.out.println(hobby);
        return "OK";
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值