如何使用 spring mvc 在 REST POST 方法中传递 List<>

bag*_*gui 4 java rest spring spring-mvc

我正在尝试使用 spring mvc 在 REST post 方法的请求正文中传递类似值的列表。下面是我的示例代码。请让我知道在 requestbody 中发送列表的正确方法是什么。

@RequestMapping(value = "/userlogin/details", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public ResponseEntity<String> insertLoginDetails(
        @RequestParam("username") String userName,
        @RequestBody List<String> listOfID) {
    return eventAnalyzerHelper.insertUserLoginDetails(userName,
            listOfID);
}
Run Code Online (Sandbox Code Playgroud)

谢谢

Ank*_*hal 6

这个例子可能对你有帮助

每个text input都有相同的名字水果:

<form method="post">
  Fruit 1: <input type="text" name="fruits"/><br/>
  Fruit 2: <input type="text" name="fruits"/><br/>
  Fruit 3: <input type="text" name="fruits"/><br/>
  <input type="submit"/>
</form>
Run Code Online (Sandbox Code Playgroud)

在您的 上controller’s handler method,您可以通过如下绑定来获取所有水果名称的列表:

@RequestMapping(value = "/", method = RequestMethod.POST)
public String addFruits(@RequestParam("fruits") List<String> fruits) {
  // ...
}
Run Code Online (Sandbox Code Playgroud)

基本上 Spring 自己处理,如果您有多个具有相同路径/名称的字段,它会自动尝试将其转换为数组或列表。