我正在使用 Spring + Thymeleaf,我有 List<Hobby>
在我的 POJO 中,此列表设置为模型属性,然后在 Thymleaf 页面中显示为复选框列表。假设大小为List<Hobby>
是 5,用户从中选择了 3。
是否可以将所选项目获取为 List<Hobby>
回到 Controller ?
我们知道您可以轻松地将其获取为 String[]
{value1,value2,value3}
最佳答案
您可以创建扩展 CustomCollectionEditor 的 HobbyEditor,重写 ConvertElement 方法并在 initbinder 中绑定(bind)相同的方法
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));
}
关于java - 获取复选框选定的值作为 List<Objects>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35407624/