简体   繁体   中英

Passing list of data from JSP to Set in Java

I use the Struts2 framework. In my action class I have a Set<Item> attribute with getters and setters:

private Set<Item> items;

public Set<Item> getItems()
{
    return items;
}

public void setItems(Set<Item> items)
{
    this.items = items;
}

On my JSP I have the following form:

<form action='...'>
    <input type="hidden" name="items.id" value="4592"/>
    <input type="hidden" name="items.id" value="5016"/>
    <input type="hidden" name="items.id" value="3227"/>
    <input type="hidden" name="items.id" value="8549"/>
</form>

I expected that form, when submitted to my action class, would result in a Set<Item> with 4 Item objects to be created and each of those Items would have their Id attribute set to the given value. However, when I run this, the set is empty (no elements).

What's really strange is that my logging of this action:

ACTIONCLASS - GET the set of items in action class
ACTIONCLASS - SET the set of item in action class
ACTIONCLASS - After setting the set, the set of items is EMPTY
ITEMCLASS - now creating a new ITEM object
ITEMCLASS - SET id of item to value: 4592
ITEMCLASS - now creating a new ITEM object
ITEMCLASS - SET id of item to value: 5016
ITEMCLASS - now creating a new ITEM object
ITEMCLASS - SET id of item to value: 3227
ITEMCLASS - now creating a new ITEM object
ITEMCLASS - SET id of item to value: 8549
ACTIONCLASS - now starting the execute() method
ACTIONCLASS - the set of items is EMPTY

As you can see, the items are created and their id's are being set! But unfortunately, the are not added to the set. Why is this?

What do I need to change about the line below to make it work as intented?

<input type="hidden" name="items.id" value="8549"/>

NOTE: If I change Set to List in my action class, this code works. But I really would like to work with a Set instead of a List .

The name is needed to use parentheses, like

<s:hidden name="items(%{#status.index}).id" value="8549"/> 

Supposed it's used with iterator.

Annotations to use with the Set property

@Element(value = Item.class)
@Key(value = Integer.class)
@KeyProperty(value = "id") 
@CreateIfNull(value = true)
private Set<Item> items = new HashSet(0);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM