Reputation: 844
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.
@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
Upvotes: 4
Views: 21310
Reputation: 853
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) {
// ...
}
Upvotes: 0
Reputation: 26057
This example might help you
Each text input
has the same name fruits:
<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:
@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.
Upvotes: 6