Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Spring-绑定到对象而不是字符串或基元_Spring_Data Binding_Spring Mvc - Fatal编程技术网

Spring-绑定到对象而不是字符串或基元

Spring-绑定到对象而不是字符串或基元,spring,data-binding,spring-mvc,Spring,Data Binding,Spring Mvc,假设我有以下命令对象: class BreakfastSelectCommand{ List<Breakfast> possibleBreakfasts; Breakfast selectedBreakfast; } class BreakfastSelectCommand{ 列出可能的漏洞; 早餐精选早餐; } 如何让spring用列表中的早餐填充“Selected早餐” 我想我应该在jsp中执行类似的操作: <form:radiobuttons item

假设我有以下命令对象:

class BreakfastSelectCommand{
    List<Breakfast> possibleBreakfasts;
    Breakfast selectedBreakfast;
}
class BreakfastSelectCommand{
列出可能的漏洞;
早餐精选早餐;
}
如何让spring用列表中的早餐填充“Selected早餐”

我想我应该在jsp中执行类似的操作:

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

但这似乎不起作用。有什么想法吗

谢谢


-摩根银行

这一切的关键是房地产编辑

您需要为早餐类定义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));
    }
}
注意事项:

  • PropertyEditor不是线程安全的
  • 如果您需要Springbean,可以手动注入它们,或者在spring中将它们定义为原型范围,并将方法注入到您的控制器中
  • 抛出IllegalArgumentException如果入站参数无效/未找到,spring会将其正确转换为绑定错误
希望这有帮助

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


根据DAO对象的实现,调用它们两次或尝试加载同一实体两次并不意味着您将运行两条SQL语句。这尤其适用于Hibernate,在Hibernate中,它保证它将返回给定标识符的会话中的同一对象,因此运行时允许绑定尝试加载
早餐
选择,即使它没有更改,也不会导致任何不必要的开销。

谢谢gid。在绑定时,是否已经创建了我的命令对象(第二次)?奇怪的是,我还需要向幽道提出另一个要求。