I'm sending some parameters from a form in this way:
myparam[0] : 'myValue1'
myparam[1] : 'myValue2'
myparam[2] : 'myValue3'
otherParam : 'otherValue'
anotherParam : 'anotherValue'
...
I know I can get all the params in the controller method by adding a parameter like
public String controllerMethod(@RequestParam Map<String, String> params){
....
}
I want to bind the parameters myParam[] (not the other ones) to a list or array (anything that keeps the index order), so I've tried with a syntax like:
public String controllerMethod(@RequestParam(value="myParam") List<String> myParams){
....
}
and
public String controllerMethod(@RequestParam(value="myParam") String[] myParams){
....
}
but none of them are binding the myParams. Even when I add a value to the map it is not able to bind the params:
public String controllerMethod(@RequestParam(value="myParam") Map<String, String> params){
....
}
Is there any syntax to bind some params to a list or array without having to create an object as @ModelAttribute with a list attribute in it?
Thanks
One way you could accomplish this (in a hackish way) is to create a wrapper class for the
List
. Like this:Then your controller method signature would look like this:
No need to use the
@RequestParam
or@ModelAttribute
annotation if the collection name you pass in the request matches the collection field name of the wrapper class, in my example your request parameters should look like this:Or you could just do it that way:
That works for example for forms like this:
This is the simplest solution :)
Subscribing what basil said in a comment to the question itself, if
method = RequestMethod.GET
you can use@RequestParam List<String> groupVal
.Then calling the service with the list of params is as simple as:
Arrays in
@RequestParam
are used for binding several parameters of the same name:If you need to bind
@ModelAttribute
-style indexed parameters, I guess you need@ModelAttribute
anyway.Just complementing what Donal Fellows said, you can use List with @RequestParam
Hope it helps!
It wasn't obvious to me that although you can accept a Collection as a request param, but on the consumer side you still have to pass in the collection items as comma separated values.
For example if the server side api looks like this:
Directly passing in a collection to the RestTemplate as a RequestParam like below will result in data corruption
Instead you can use
The complete example can be found here, hope it saves someone the headache :)