Home > DeveloperSection > Forums > Binding a list in @RequestParam
Mary Johnson
Mary Johnson

Total Post:3

Points:21
Posted on    December-16-2015 12:08 AM

 Java Java  Collection 
Ratings:


 1 Reply(s)
 308  View(s)
Rate this:
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?


Mayank Tripathi
Mayank Tripathi

Total Post:397

Points:3117
Supported
Posted on    December-16-2015 12:17 AM

Arrays in @RequestParam are used for binding several parameters of the same name:

myparam=myValue1&myparam=myValue2&myparam=myValue3
If you need to bind @ModelAttribute-style indexed parameters, I guess you need @ModelAttribute anyway.

Or you could just do it that way:

public String controllerMethod(@RequestParam(value="myParam[]") String[] myParams){
    ....
}
That works for example for forms like this:

<input type="checkbox" name="myParam[]" value="myVal1" />
<input type="checkbox" name="myParam[]" value="myVal2" />

Don't want to miss updates? Please click the below button!

Follow MindStick