2009-02-05 71 views
6

比方说,我有以下命令对象:春天 - 绑定到一个对象,而不是字符串或原始

class BreakfastSelectCommand{ 
    List<Breakfast> possibleBreakfasts; 
    Breakfast selectedBreakfast; 
} 

我怎么能有春天填入“selectedBreakfast”从列表中的早餐?

我盘算我会做这样的事情在我的jsp:

<form:radiobuttons items="${possibleBreakfasts}" path="selectedBreakfast" /> 

但这似乎并没有工作。有任何想法吗?

感谢,

-Morgan

回答

8

它所有这一切的关键是属性编辑器。

您需要为您的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(); 
    } 
} 

笔记,知道你们需要一些空检查等,但你的想法。在你的控制器:

public BreakfastFooBarController extends SimpleFormController { 
    @Override 
    protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) { 
     binder.registerCustomEditor(Breakfast.class, new BreakfastPropertyEditor(yourDao)); 
    } 
} 

事情需要提防:

  • 属性编辑器的不是线程安全的
  • ,如果你需要的Spring bean,可以手动将它们注入或在春季将它们定义为原型范围和使用方法注入您的控制器
  • throw IllegalArgumentException如果入站参数无效/未找到,spring会将其正确转换为绑定错误

希望这有助于。

编辑(回复此评论): 在给出的例子中,它看起来有点奇怪,因为BreakfastSelectCommand看起来不像一个实体,我不确定你的实际场景是什么。假设它是一个实体,例如Person带有breakfast属性,那么formBackingObject()方法将从PersonDao加载Person对象并将其作为命令返回。然后,绑定阶段将根据所选值改变早餐属性,使得到达onSubmit的命令具有所有设置的早餐属性。

根据DAO对象的实现调用它们两次或试图加载同一个实体两次实际上并不意味着您将得到两个正在运行的SQL语句。这特别适用于Hibernate,它保证它会返回给定标识符的会话中相同的对象,因此运行让绑定尝试加载选项,即使它没有改变也不应该导致任何结果不必要的开销。

+0

谢谢gid。在绑定的时候,我的命令对象是不是已经创建(第二次)?这似乎很奇怪,我应该需要再提出一个请求。 – morgancodes 2009-02-11 23:35:30

相关问题