2

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.

2
  • What are you using for view resolver? Thymeleaf, JSP? Commented Jul 25, 2017 at 20:01
  • You need to use SpEl (${prop}). Where is prop coming from? Show complete code to get better help Commented Jul 25, 2017 at 20:02

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.