mor*_*des 6 data-binding spring spring-mvc
假设我有以下命令对象:
class BreakfastSelectCommand{
List<Breakfast> possibleBreakfasts;
Breakfast selectedBreakfast;
}
Run Code Online (Sandbox Code Playgroud)
如何从名单中选择含早餐的"selectedBreakfast"?
我在想我在jsp中做这样的事情:
<form:radiobuttons items="${possibleBreakfasts}" path="selectedBreakfast" />
Run Code Online (Sandbox Code Playgroud)
但这似乎不起作用.有任何想法吗?
谢谢,
-摩根
所有这一切的关键是PropertyEditor.
您需要为Breakfast类定义PropertyEditor,然后使用控制器的initBinder方法中的registerCustomEditor配置ServletDataBinder.
例:
public class BreakfastPropertyEditor extends PropertyEditorSupport{
public void setAsText(String incomming){
Breakfast b = yourDao.findById( Integer.parseInt(incomming));
setValue(b);
}
public String getAsText(){
return ((Breakfast)getValue()).getId();
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,您将需要一些空检查等,但您明白了.在你的控制器中:
public BreakfastFooBarController extends SimpleFormController {
@Override
protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) {
binder.registerCustomEditor(Breakfast.class, new BreakfastPropertyEditor(yourDao));
}
}
Run Code Online (Sandbox Code Playgroud)
需要注意的事项:
希望这可以帮助.
编辑(响应评论):在给定的例子中看起来有点奇怪,因为BreakfastSelectCommand看起来不像实体,我不确定你的实际情况是什么.假设它是一个实体,例如Person与breakfast属性一样,那么该formBackingObject()方法将从该对象加载Person对象PersonDao并将其作为命令返回.然后,绑定阶段将根据所选值更改早餐属性,使得到达的命令onSubmit具有全部设置的早餐属性.
根据您的DAO对象的实现调用它们两次或尝试两次加载相同的实体并不意味着您将获得两个运行的SQL语句.这特别适用于Hibernate,它保证它将返回给定标识符在其会话中的同一对象,从而运行让绑定尝试加载Breakfast选择,即使它没有改变也不会导致任何过度高架.
| 归档时间: |
|
| 查看次数: |
7243 次 |
| 最近记录: |