Spring MVC databinding using lists and checkboxes

前端 未结 1 2075
有刺的猬
有刺的猬 2021-01-25 14:27

I know questions on this matter have been asked already, but none of the answers I found solved my problem.

I have a many-to-many relantionship on my database. I\'m usin

相关标签:
1条回答
  • 2021-01-25 15:07

    Apparently, the List comming from the checkbox was actually an array of Strings, which could not be converted to a List of Tags, as defined the model classes.

    I solved my problem by creating a custom PropertyEditor, which would allow me to bind the checkboxes with the list of tags.

    public class TagPropertyEditor extends PropertyEditorSupport {
    
        private TagService tagService;
    
        public TagPropertyEditor(TagService tagService){
            this.tagService = tagService;
        }
    
        @Override
        public String getAsText() {
            return ((Tag) getValue()).getId().toString();
        }
    
        @Override
        public void setAsText(String incomingId) throws IllegalArgumentException {
            Tag tag = tagService.getTag(Integer.valueOf(incomingId));
            setValue(tag);
        }
    }
    

    And then registering on my BookController:

    //...
    @InitBinder
    public void initBinder(WebDataBinder binder){
        binder.registerCustomEditor(Tag.class, new TagPropertyEditor(tagService));
    }
    

    And this is the checboxes tag on my JSP:

     <form:checkboxes path="tags" 
                      items="${tags}"
                      itemLabel="description"
                      itemValue="id"/>
    
    0 讨论(0)
提交回复
热议问题