How do I bind collection attributes to a form in Spring MVC

I'm trying to bind one of my model objects to the fields of a form, using Spring-MVC. Everything works fine, except that one of the attributes of the model object is an unordered collection. Doing something like

    <c:forEach items="${m.items}" var="i" varStatus="itemsRow">
      <form:input path="items[${itemsRow.index}]"/>
    <form:errors path="items" />

would work fine for a List-type property, but for a Set throws an error when, upon submit, it tries to bind input field content to object attributes.

Is there something in Spring that works out of the box with Sets?

Asked by: Julian989 | Posted: 28-01-2022

Answer 1

I think it has to be an ordered collection. For example,there's a chart in the Spring reference that talks about how to reference properties. It says:

account[2] Indicates the third element of the indexed property account. Indexed properties can be of type array, list or other naturally ordered collection (emphasis theirs)

Perhaps one approach would be to add a getter to your object that, rather than returning your Set, returns Set.toArray(). Then your items attribute would reference the array. Of course, you can't depend on the ordering.

Answered by: Eric911 | Posted: 01-03-2022

Answer 2

I think the reason that it doesn't work with a Set is because a the order of a Set is not guaranteed. When you try to bind to the first object on post, it may not have been the first object in that list to render out. For example, items[0] may not be the same between the GET and the POST.

So it should work fine if you use an implementation of Set that is ordered, such as a SortedSet or TreeSet.

Answered by: Robert337 | Posted: 01-03-2022

Answer 3

found perfect solution here:

general idea - using commons-collections methods to init list:

private List someList = LazyList.decorate(new ArrayList(), FactoryUtils.instantiateFactory(;

Answered by: Maddie558 | Posted: 01-03-2022

Answer 4

I am not crystal clear on how exactly this gets bound, but it works for my purposes.

 <c:forEach items="${items}" var="i" varStatus="itemsRow">
        <input name="items[${itemsRow.index}].fieldName" type="text"/>
 <form:errors path="items" />

Answered by: Melissa709 | Posted: 01-03-2022

Answer 5

You could try writing your own custom Editor to do the job, and then registering the editor with the controller for the form. You wouldn't have to bother with indexing the elements in the Set that way. And as previously mentioned, if there's a way of sorting the elements, you could ensure their order in the set using SortedSet.

Answered by: Briony587 | Posted: 01-03-2022

Answer 6

You can use a semi-colon-delimited list if you're using numeric references to the IDs of objects, and an appropriate Converter implementation registered.

POST data leaderboards=1,2

Converter implementation (ignore the JSON stuff)

    public final class LeaderboardConverter extends JsonDeserializer<Leaderboard> implements Converter<String, Leaderboard>
        public Leaderboard convert(String source) throws IllegalArgumentException
            Leaderboard activity = new Leaderboard();
            activity.setId(new Integer(source));
            return activity;

        public Leaderboard deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException
            return convert(jp.getText());


Answered by: John451 | Posted: 01-03-2022

Similar questions

How do I use Java getters and setters with a collection of data without explicitly typing out the attributes for each item?

I am very new to Java and to programming in general, and I have an assessment to complete where I load employees (with name, age, and department attributes; department can be only one of four enumerated values) into a program that will sort them by age and tell if the age is a prime number. The assignment requires Company, Department, and Employee classes. I am confident that I can figure out age/prime components — I kno...

java - How to fetch lazy attributes in collection of entities, by not doing N calls to database

How to fetch lazy attributes in collection of entities, by not doing N calls to database. Example: transactions = getTransactionsBySomeCriteriaApiQuery(..); // n transactions // this make 3*n calls to DB, I want to do only a few calls transactions.forEach(res -&gt; { res.getLazyCollection1().size(); res.getLazyCollection2().size(); res.getLazyCollection3().size()...

How to check Not Null for all the attributes of a Model in a Collection in java using Optional?

Lets say there is a List&lt;Student&gt;. Each Student have two properties name and Id. I need to check each one of the Student in the list and check each of the two properties. if Both properties and the student object itself are not null then print that student. All using java 8 Optional.

java - Sort collection according to user custom input by single or multiple attributes

I have collection of Item object and the class Item is as follows -&gt; class Item { String id; String brand; Integer price; Date publishedDate; } Now, I want to sort according to the user input. User can sort it according to his choice like brand, price or publishedDate and even with the multiple parameters. Like brand and price or price and publishedDate. I have seen Compara...

java - Illegal attempt to associate a collection with two open sessions

I'm trying to add a pojo to a collection in another pojo. I'm sure I'm making a really stupid mistake somewhere along the lines but I can't figure out how to solve it. I have a pojo LookupTable which contains a list of Columns: public class LookupTable { private long id; // More properties go here... private List&lt;Column&gt; columns; public void addColumn(Column column) { this.columns...

garbage collection - Java Concurrent and Parallel GC

This article here suggests to use -XX:+UseParNewGC "To enable a parallel young generation GC with the concurrent GC". My confusion is that in order to enable both parallel and concurrent GC, should I use -XX:+UseParNewGC or use both -XX:+UseParNewGC and -XX:+Use...

java - Printing out items in any Collection in reverse order?

I have the following problem in my Data Structures and Problem Solving using Java book: Write a routine that uses the Collections API to print out the items in any Collection in reverse order. Do not use a ListIterator. I'm not putting it up here because I want somebody to do my homework, I just can't seem to understand exactly what it is asking for me to code! W...

java - Best Collection To Use?

Does using final for variables in Java improve garbage collection?

Today my colleagues and me have a discussion about the usage of the final keyword in Java to improve the garbage collection. For example, if you write a method like: public Double doCalc(final Double value) { final Double maxWeight = 1000.0; final Double totalWeight = maxWeight * value; return totalWeight; } Declaring the variables in the method final

generics - Java: How to create a collection of a specific parent type and not its subtypes?

I am learning Java for a test (tomorrow) and am wondering about a question that will probably never come up but has got me curious. Is it possible to create a new collection class such as a list or something that can hold only a specific type and not its sub-types? Would I use generics to achieve this goal?

java - Can Hibernate return a collection of result objects OTHER than a List?

Does the Hibernate API support object result sets in the form of a collection other than a List? For example, I have process that runs hundreds of thousands of iterations in order to create some data for a client. This process uses records from a Value table (for example) in order to create this output for each iteration. With a List I would have to iterate through the entire list in order to find a certa...

java - JPA map collection of Enums

Is there a way in JPA to map a collection of Enums within the Entity class? Or the only solution is to wrap Enum with another domain class and use it to map the collection? @Entity public class Person { public enum InterestsEnum {Books, Sport, etc... } //@??? Collection&lt;InterestsEnum&gt; interests; } I am using Hibernate JPA implementation, but of course would prefer implem...

c# - garbage collection Operation

Can someone please explain me how garbage collection is working? (I'm using C# and Java).

Java: Trouble with Generics & Collection type detection

I have a class called DataSet with various constructors, each specifying a different type of variable. It might look a bit like this: public class DataSet { private HashSet Data; public DataSet( DataObject obj ) { Data = new &lt;DataObject&gt;HashSet(); Data.add( obj ); } public DataSet( ObjectRelationship rel ) { Data = new &lt;ObjectRelationship&gt;HashS...

Still can't find your answer? Check out these amazing Java communities for help...

Java Reddit Community | Java Help Reddit Community | Java Community | Java Discord | Java Programmers (Facebook) | Java developers (Facebook)