Announcement Announcement Module
Collapse
No announcement yet.
Use collection property name to set allowed fields in DataBinder Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Use collection property name to set allowed fields in DataBinder

    Hello,

    I try to set fields allowed for data binding. I have list field called items. Why should I do dataBinder.setAllowedFields("items*") instead of dataBinder.setAllowedFields("items"). Can it be considered as a bug?


    package util;

    import static org.junit.Assert.assertEquals;
    import static org.junit.Assert.*;

    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;

    import org.junit.Ignore;
    import org.junit.Test;
    import org.springframework.beans.MutablePropertyValues;
    import org.springframework.validation.DataBinder;

    public class SpringDataBinderAllowCollectionBindingTest {

    @Ignore("Collection field name can't be used to specify allowed fields for binding. Should use field name pattern instead. Why?")
    @Test
    public void testAllowCollectionBinding() {
    testWithAllowedFields("items");
    }

    @Test
    public void testAllowCollectionBindingViaPattern() {
    testWithAllowedFields("items*");
    }

    private void testWithAllowedFields(String... allowedFields) {
    Map<String, String> data = new HashMap<>();
    data.put("items[0]", "First item");
    data.put("items[1]", "Second item");

    DataBinder binder = new DataBinder(new CollectionHolder());
    binder.setAllowedFields(allowedFields);
    binder.bind(new MutablePropertyValues(data));

    CollectionHolder result = (CollectionHolder) binder.getTarget();

    assertNotNull(result.items);
    assertEquals(2, result.items.size());
    assertTrue(result.items.contains("First item"));
    assertTrue(result.items.contains("Second item"));
    }


    public static class CollectionHolder {

    private List<String> items;

    public CollectionHolder(List<String> items) {
    super();
    this.items = items;
    }

    public CollectionHolder() { }

    public List<String> getItems() {
    return items;
    }

    public void setItems(List<String> items) {
    this.items = items;
    }

    }
    }

  • #2
    This question is probably a better candidate for StackOverflow, perhaps with the "spring" tag.

    Could you post your question there?
    The forums are moving to stackoverflow, a page explaining all this will be available there in a few days: http://spring.io/questions

    Comment

    Working...
    X