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 @RequestParam annotation.

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

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) {
  // ...
}

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

Advertisements

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

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s