简体   繁体   中英

Get checkbox selected values as List<Objects>

I'm using Spring + Thymeleaf, I have List<Hobby> in my POJO and this list is set to model attribute which is then display in a Thymleaf page as list of checkbox. Suppose the size of List<Hobby> is 5 and user selected 3 from it.

Is it possible to get the selected items as List<Hobby> back to the Controller? We know that you can easily get this as String[] {value1,value2,value3}

You can create HobbyEditor that extends CustomCollectionEditor, override convertElement method and bind the same in initbinder

import java.util.Collection;
import java.util.List;

public class HobbyEditor extends CustomCollectionEditor  {

  @SuppressWarnings("rawtypes")
  public HobbyEditor(Class<? extends Collection> collectionType) {
     super(collectionType);

  }

  @Override
  protected Object convertElement(Object element) {

     if (element instanceof Hobby) {
         return element;
     }
     if (element instanceof String) {
         Hobby  h = new Hobby((String)element);
         return h;
     }
     return null;
  }

}

@InitBinder
protected void initBinder(WebDataBinder binder) {

    binder.registerCustomEditor(List.class, "hobby", new HobbyEditor(List.class));

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM