Binding a List Request Parameter on Spring MVC

Here’s another handy stuff I found on Spring MVC, if you have an unknown number of elements on your form (say a fruit basket), you can bind them into a List with annotation.

Let’s say this is our form:
spring-bind-list

Each text input has the same name fruits:


Fruit 1:
Fruit 2:
Fruit 3:

On your controller’s handler method, you can obtain the list of all fruit names by binding it like this:

(value = "/", method = RequestMethod.POST)
public String addFruits(("fruits") List fruits) {
  // ...
}

The order of fruit names added to the list will be the same as the order of your form text inputs.

One thought on “Binding a List Request Parameter on Spring MVC”

Leave a Reply