java 如何使用 spring mvc 在 REST POST 方法中传递 List<>
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25277566/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to pass a List<> in REST POST method using spring mvc
提问by bagui
I'm trying to pass a List of similar values in the request body of a REST post method using spring mvc. Below is my sample code. Please let me know what is correct way to send the List in requestbody.
我正在尝试使用 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);
}
Thanks
谢谢
回答by Ankur Singhal
This example might help you
这个例子可能对你有帮助
Each text input
has the same name fruits:
每个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>
On your controller's handler method
, you can obtain the list of all fruit names by binding it like this:
在您的 上controller's handler method
,您可以通过如下绑定来获取所有水果名称的列表:
@RequestMapping(value = "/", method = RequestMethod.POST)
public String addFruits(@RequestParam("fruits") List<String> fruits) {
// ...
}
Basically Spring handles on its own, if you have multiple fields with same path/name, it automatically tries to cast it into Array or List.
基本上 Spring 自己处理,如果您有多个具有相同路径/名称的字段,它会自动尝试将其转换为数组或列表。
回答by Khush
You will need to wrap the List in an Object. Its better designed that way. You could make this object generic and reuse it multiple times in other controllers if needed. Just be aware that you have to follow the same structure when constructing the object in the calling system.
您需要将列表包装在一个对象中。这样设计得更好。如果需要,您可以使这个对象通用并在其他控制器中多次重用它。请注意,在调用系统中构造对象时必须遵循相同的结构。
@RequestMapping(value = "/", method = RequestMethod.POST)
public String addFruits(@RequestBody ListWrapper fruits) {
// ...
}