【问题标题】:Spring 3 MVC: how to make a form with comma-separated set of stringsSpring 3 MVC:如何使用逗号分隔的字符串集制作表单
【发布时间】:2011-12-09 11:05:24
【问题描述】:

我是 Spring 3 的新手,我不知道解决问题的最佳方法。

我有一个实体想法:

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

其中有几个相关的标签。 我想创建一个表单,在其中我可以在一个输入中给出逗号分隔的标签列表(与stackoverflow中的相同)。 而且我需要一种解析器,它用这些逗号分割字符串并将每个标签添加到这个想法中。 我该如何正确地做到这一点?

我现在的表格是这样的:

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

并且输入中当前显示的文本是“[]”(必须是HashSet类的toString方法)。

顺便说一句,我使用 Spring 3.0.5、Hibernate 和 JSP。

编辑:我可以创建一个专用类吗:

public class IdeaForm {
    String tags;
}

然后创建一个实用程序类,将逗号分隔的标签映射到一个集合?

谢谢!

【问题讨论】:

    标签: spring-mvc spring-3


    【解决方案1】:

    终于在我的控制器中使用了 initBinder 工具:

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

    并创建了我的自定义编辑器

    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);
        }
    

    }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-07-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多