当浏览器发起数组集合参数的请求时,服务端只需要保证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";
}
}