A. K.
A. K.

Reputation: 311

Easy way to submit an array field with Spring MVC forms?

I have a form with a list of nested fieldsets corresponding to a collection of objects, backed by a form object server-side. Fieldsets can be added or removed client-side. I want to submit a form without caring about object indices or sparse lists in command object.

Here's my Controller method code:

@PostMapping("/foobar")
public String doPost(FoobarForm form) {
    //...
}

In PHP, Rails etc it's very easy:

<input name="prop[]">

, and it will automatically populate $_POST["prop"] with all the values.

Working with Spring MVC, I tried these things:

  1. <input name="prop[]"> - doesn't work saying Invalid property 'prop[]' of bean class [...]: Invalid index in property path 'prop[]'; nested exception is java.lang.NumberFormatException: For input string: ""

  2. <input name="prop"> - will not bind to a list-typed bean property, even when multiple fields present.

  3. <input name="prop[${i}]"> - implies all that hassle with sparse list and index handling, both client-side and server-side. Certainly not the right way to do things when working with a powerful web framework.

I'm wondering why can't I just use [] in property name and let Spring create a list automatically? It was asked three times on Spring JIRA without any reasonable responses.

Upvotes: 2

Views: 2900

Answers (2)

Oleksandr Potomkin
Oleksandr Potomkin

Reputation: 339

I found the answer here.
You can use the MultiValueMap<String, String>

@RequestMapping("foo")
public String bar(@RequestParam MultiValueMap<String, String> parameters){ ... }

With these two inputs:

<input name="prop" value="One">
<input name="prop" value="Two">

the result will be {prop=["One","Two"]}

The code below will work too.

public String bar(@RequestParam("prop") List<String> props){ ... }

Upvotes: 0

Biraj Sahoo
Biraj Sahoo

Reputation: 44

Spring form binding makes this more easy. You need to add List object in your bean and bind that in jsp using spring form.

class FoobarForm {
  List<String> prop;
}

In jsp, if you need to show/edit value all at once then <form:input path="prop" /> .if you want to show one by one then use indexing<form:input path="prop[0]" />. Use proper CommandName in form. It will work.

Upvotes: 1

Related Questions