当我尝试保存 miniApple 的单个值时,以下代码可以正常工作。我可以在控制器的参数中看到 miniApple 对象值的值,即苹果。但是,如果有多个值,我将无法绑定。不确定在 initBinder 方法中写入的语法应该是什么,用于将字符串(逗号分隔值)转换为自定义对象列表(此处为 MiniApple 列表)
当我选择多个值时,我可以将 setAsText() 中的文本值作为逗号分隔值(例如:“miniApple1,miniApple2,miniAPlle3”)
控制器方法 save()
public ModelAndView save(@ModelAttribute("Apple") Apple apple, BindingResult result, SessionStatus status) {
}
初始化活页夹方法
@InitBinder
public void initBinder(WebDataBinder dataBinder) {
dataBinder.registerCustomEditor(MiniApple.class, new MiniAppleEditor(this.miniAppleService, true));
}
具有 setAsText 方法的自定义编辑器类
public class MiniAppleEditor extends PropertyEditorSupport {
/** The mini apple service. */
private final MiniAppleService miniAppleService;
/** Whether or not to allow null values. */
private boolean allowEmpty;
/**
* @param miniAppleService the miniAppleService to set
*/
public MiniAppleEditor(MiniAppleService miniAppleService) {
this(miniAppleService, false);
}
/**
* @param miniAppleService the miniAppleService to set
* @param allowEmpty indicates to allow empty mini apple.
*/
public MiniAppleEditor(MiniAppleService miniAppleService, boolean allowEmpty) {
this.miniAppleService = miniAppleService;
this.allowEmpty = allowEmpty;
}
/**
* @param text the id representing the MiniApple object.
*/
@Override
public void setAsText(String text) {
if (allowEmpty && !StringUtils.hasLength(text)) {
setValue(null);
} else {
setValue(miniAppleService.getMiniApple(Integer.parseInt(text)));
}
}
/**
* @return the Id as a String
*/
@Override
public String getAsText() {
MiniApple miniApple = (MiniApple) getValue();
if (miniApple == null) {
return "";
} else {
return miniApple.getAppleName();
}
}
}
将获取绑定为控制器保存()方法的参数的值的对象
@Entity
@Table("tbl_apple")
public class Apple implements Serializable {
private MiniApple miniApple;
getter/setter;
}