Nanocom
Nanocom

Reputation: 3726

Spring 3 MVC: how to make a form with comma-separated set of strings

I am quite new in Spring 3 and I don't know the best mean to resolve my problem.

I have an entity Idea:

public class Idea {
    private Set<Tag> tags;
}

which has several related tags. I would like to create a form in which I can give a comma-separated list of tags in one input (kind of the same as in stackoverflow). And I need kind of a parser which splits the string with those commas and adds each tag to the idea. How do I do that properly?

My current form is this:

<form:form modelAttribute="idea">
    <form:input path="tags" />
</form:form>

And the current displayed text in the input is "[]" (must be the toString method of the HashSet class).

Btw, I use Spring 3.0.5, Hibernate and JSPs.

Edit: May I create a special-dedicated class:

public class IdeaForm {
    String tags;
}

And then create an utility class which maps comma-separated tags to a Set?

Thanks!

Upvotes: 1

Views: 973

Answers (1)

Nanocom
Nanocom

Reputation: 3726

Finally used the initBinder facility in my controller:

@InitBinder
public void initBinder(WebDataBinder binder) {
    binder.registerCustomEditor(Set.class, new CommaDelimitedStringEditor());
}

And created my custom editor

public class CommaDelimitedStringEditor extends PropertyEditorSupport {

    public void setAsText(String text) {
        Set<Tag> tags = new HashSet<Tag>();
        String[] stringTags = text.split(", ");
        for(int i =0; i < stringTags.length; i++) {
            Tag tag = new Tag();
            tag.setName(stringTags[i]);
            tags.add(tag);
        }
        setValue(tags);
    }

}

Upvotes: 2

Related Questions