关于前后端数组传递与接收问题@RequestParam(vue + springboot)
方法一:前端以字符串形式传递idList,采用逗号拼接,后端直接使用list接收
请求链接格式:http://localhost:9090/yycontroller/updatexx?gradeInterval=93&idList=70545,70544
方法一:(前端以字符串形式传递idList,采用逗号拼接,后端直接使用list接收)
// 前端代码:
// 1.声明请求参数
form: {
gradeInterval: '', // 曝光刻度
idList: '' // id拼接的串
},
// 2.声明空的数组,并向数组中添加元素
const ids = []
for (const item of this.multipleSelection) {
ids.push(item.id)
}
// 3.将ids的值赋给idList,为请求参数赋值
this.form = {
gradeInterval: 0,
idList: ids.join(',') // 主键如果有多个使用逗号拼接,如果只有一个则不需要拼接,直接赋值即可
}
// 4.发送请求 post方式,参数为this.form.gradeInterval、this.form.idList
// 后端代码
// 在后端接收idList时,直接使用List<T> 就可以接收前端字符串(默认使用英文逗号,做自动切分)
@RequestMapping(value = "/updatexx", method = RequestMethod.POST)
public Protocol<Boolean> updatexx(@RequestParam("gradeInterval") Integer gradeInterval, @RequestParam(value = "idList") List<Long> idList) {
if (ListHelper.isEmpty(idList)) {
return new Protocol<>(false);
}
return xxApi.update(gradeInterval, idList);
}
方法二:前端以数组形式传递,后端使用@RequestParam(value = "idList[]") List<Long> idList方式接收
请求链接格式为:http://localhost:9090/yycontroller/updateGradexx?gradeInterval=90&idList[]=70545&idList[]=70544
方法二(前端以数组形式传递,后端使用@RequestParam(value = "idList[]") List<Long> idList方式接收)
// 前端代码:
// 1.声明请求参数
form: {
gradeInterval: '', // 曝光刻度
idList: [] // 声明空的数组
},
// 2.声明空的数组,并向数组中添加元素
const ids = []
for (const item of this.multipleSelection) {
ids.push(item.id)
}
// 3.将ids的值赋给idList,为请求参数赋值
this.form = {
gradeInterval: 0,
idList: ids // 直接将ids赋给idList
}
// 4.发送请求 post方式,参数为this.form.gradeInterval、this.form.idList
// 后端代码
// 在后端接收idList时,注意在@RequestParam中声明value为idList[]格式,可以直接转换为集合
@RequestMapping(value = "/updatexx", method = RequestMethod.POST)
public Protocol<Boolean> updatexx(@RequestParam("gradeInterval") Integer gradeInterval, @RequestParam(value = "idList[]") List<Long> idList) {
if (ListHelper.isEmpty(idList)) {
return new Protocol<>(false);
}
return xxApi.update(gradeInterval, idList);
}
方法三:前端以json数组形式传递,后端使用@RequestBody List<Integer> ids方式接收
// 前端代码,采用post方式,以json数组传递数值
const xxids= [13,22]
return axios({
url: url,
method: 'post',
data: xxids,
headers: {
'Content-Type': 'application/json'
}
})
// 后端代码
// 使用@RequestBody方式接收
@PostMapping("/editIds")
public xx editIds(@RequestBody List<Integer> ids) {
return xxService.editIds(ids);
}