views:

30

answers:

1

I'm building a Spring MVC app with Spring 3.0.3. I have data binding of my form working just fine, but one of the form fields is a list of items. Hypothetically speaking, my form object looks like this:

public class MyForm {

    private String name;
    private List<String> items;

    public String getName() {
        return name;
    }
    public void setName( String value ) {
        name = value;
    }

    public List<String> getItems() {
        return items;
    }
    public void setItems( List<String> value ) {
        items = value;
    }
}

Lets say the form is being handled through a GET with a query string that looks like the following:

"/url?name=GroupName&items=Item-1&items=Item-2&items=Item-3"

As of now, the items property of my MyForm object binds just fine with a list of String values. What I'm curious about is if I can still achieve data binding if I were to change the items list type to something more specific, such as:

private List<MyListItem> items;
+1  A: 

You can achieve this by implementing your own custom java.beans.PropertyEditor for MyListItem type and registering it. In this custom property editor, you will be able to define how the string property will be converted to your MyListItem object and vice versa by implementing the getAsText() and setAsText() methods. Spring will then use your custom PropertyEditor when binding values to your form and will be able to convert an instantiate MyListItem objects from the strings in POST/GET data.

See this link from Spring documentation for more on this. See section 5.4.2.1

Also note that this approach not only works for converting between Strings and your own custom types, but it is also useful to apply any kind of modifications to data of basic Java types at the time the form data is bound to your beans or is read from them. For instance, applying HTML escaping to string text.

Samit G.
Does this approach work with Spring 3? I failed to mention I'm using 3.0.3
Matt W
yes it will - http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/validation.html
Samit G.