How to pass a List<> in REST POST method using spring mvc
19,932
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.
Author by
bagui
Updated on June 07, 2022Comments
-
bagui almost 2 years
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
-
Sotirios Delimanolis over 9 yearsYou don't send anything in a request body, you receive from the request body. What's wrong with what you have?
-
Matt over 9 yearsI usually make a dedicated FooList class that holds a
List<Foo>
field. That way the JSON ends up being something like:{"foos": [ {"a":1}, {"b":2}, ... ] }
.
-
-
Serge Ballesta over 9 yearsEven if ankur-singhal answer is form related, a controller does not care about how the request was constructed, and you can still construct it with javascript or any other scripting language.
-
S.K. Venkat almost 8 yearsCan you plz share a example for ListWrapper class to construct the list of fruits?