【问题标题】:Get checkbox selected values as List<Objects>获取复选框选定值作为 List<Objects>
【发布时间】:2016-05-26 06:14:50
【问题描述】:

我正在使用 Spring + Thymeleaf,我的 POJO 中有List&lt;Hobby&gt;,并且此列表设置为模型属性,然后在 Thymleaf 页面中显示为复选框列表。假设List&lt;Hobby&gt; 的大小为 5,用户从中选择了 3。

是否可以将所选项目以List&lt;Hobby&gt; 的形式返回给控制器? 我们知道您可以通过 String[] {value1,value2,value3} 轻松获得此信息

【问题讨论】:

  • 你是否重写了 Hobby 类中的 equals 和 hashCode 方法?尝试添加此方法,如果您有兴趣,您将获得选择列表。

标签: java spring list checkbox


【解决方案1】:

您可以创建扩展 CustomCollectionEditor 的 HobbyEditor,覆盖 convertElement 方法并在 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));

}

【讨论】:

  • initBinder 方法必须在控制器中
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-20
  • 1970-01-01
相关资源
最近更新 更多