如何使用Spring Boot在API删除方法中传递多个ID

时间:2019-09-13 15:51:43

标签: spring rest api

我正在使用Spring Boot 1.5。我试图在DELETE中传递多个ID,所以我试图传递一个ID列表并浏览它们以应用delete方法,但是它没有字,请帮忙。

@RequestMapping(value = "/deleteAlert/{ids}", method = RequestMethod.DELETE)
ResponseEntity<Void> massiveDelete(@PathVariable List<Long> ids ){
    for (Long id : ids) {
    alertService.deleteAlert(id);}
    return ok().build();
}

因此,删除所有具有选定ID的警报

2 个答案:

答案 0 :(得分:0)

您可以将ID作为参数发送,例如deleteAlert/ids=ID1&ids=ID2&ids=ID3 注意,这些参数具有相同的名称“ ids”

然后将其作为字符串列表获取

@RequestMapping(value = "/deleteAlert", method = RequestMethod.DELETE)
ResponseEntity massiveDelete(@RequestParam("ids") List<String> idsList) 
{ 
   for (String id : idsList) {
     alertService.deleteAlert(Long.parseLong(id));
   }

   return ok().build();
}

答案 1 :(得分:0)

我不确定我是否能解决您的问题,也许指定什么是行不通的。

但是,如果我做对了,您想将ID列表传递给DELETE端点。

您实际使用的方式,我刚刚用curl对其进行了测试。

代码:

@Controller
public class ControllerImpl {
    @RequestMapping(value = "/deleteAlert/{ids}", method = RequestMethod.DELETE)
    public ResponseEntity<Void> massiveDelete(@PathVariable List<Long> ids){
        for (Long id : ids) {
            System.out.println(id);
        }
        return ok().build();
    }
}

请求: curl -X DELETE "localhost:8080/deleteAlert/1,2"

输出:

2019-09-13 19:15:12.156  INFO 27347 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 27 ms
1
2

因此api调用有效。那么也许您的问题出在您调用api的方式上?