以下のコードは、miniApple の単一の値を保存しようとすると正常に動作します。コントローラーの引数、つまりappleでminiAppleオブジェクト値の値を確認できます。ただし、複数の値がある場合はバインドできません。文字列 (カンマ区切りの値) をカスタム オブジェクトのリスト (ここでは MiniApple のリスト) に変換するために initBinder メソッド内に記述する構文がどうあるべきかわからない
複数の値を選択すると、setAsText() のテキスト値をコンマ区切りの値にすることができます (例: "miniApple1, miniApple2,miniAPlle3")
コントローラーメソッド save()
public ModelAndView save(@ModelAttribute("Apple") Apple apple, BindingResult result, SessionStatus status) {
}
Init Binder メソッド
@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();
}
}
}
コントローラの save() メソッドの引数としてバインドされた値を取得するオブジェクト
@Entity
@Table("tbl_apple")
public class Apple implements Serializable {
private MiniApple miniApple;
getter/setter;
}