【问题标题】:How to pass multiple ids in API delete method using Spring Boot如何使用 Spring Boot 在 API 删除方法中传递多个 id
【发布时间】:2019-09-13 15:51:43
【问题描述】:

我正在使用spring boot 1.5。我试图在DELETE中传递多个ID,所以我尝试传递一个ID列表并浏览它们以应用删除方法,但它没有字,请帮助。

@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 的警报

【问题讨论】:

    标签: spring rest api


    【解决方案1】:

    我不确定我是否正确解决了您的问题,也许请具体说明什么是行不通的。

    但如果我做对了,您希望将 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的方式?

    【讨论】:

      【解决方案2】:

      您可以将 ID 作为参数发送,例如 deleteAlert/ids=ID1&amp;ids=ID2&amp;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();
      }
      

      【讨论】:

      • 比您提供的帮助很多,但我需要从后端获取 id 列表,所以我试图找出如何应用到每个给定的 Id(类型 Long )方法 delete (这个方法只为一个给定的 id 实现)
      • 答案确实检索了一个 ID 列表作为字符串列表。您只需将 id 作为参数添加到前端 /deleteAlert/ids=[first_id]&amp;ids=[second_id] 我已经编辑了答案以显示如何将 id 应用于您的 deleteAlert() 方法。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-07-10
      • 2020-05-05
      • 2017-12-14
      • 2021-09-28
      • 2020-07-18
      • 1970-01-01
      • 2019-04-29
      相关资源
      最近更新 更多