[英]Spring automatic binding for dropdown lists for bean properties
有没有一种方法可以使用spring的form.select为另一种类型的bean绑定bean属性。 例:
我有一个需要在视图中使用称为BeanB的属性更新的bean:
public class BeanA {
private BeanB bean;
private int id;
private void setId(int id){
this.id = id;
}
private int getId(){
return this.id;
}
public void setBean(BeanB bean){
this.bean = bean;
}
public BeanB getBean(){
return this.bean;
}
}
public class BeanB{
private int id;
private void setId(int id){
this.id = id;
}
private int getId(){
return this.id;
}
}
对于该视图,我想发送一个使用Spring的formcontroller进行选择的BeanB列表:
public class MyController extends SimpleFormController{
protected ModelAndView handleRenderRequestInternal(RenderRequest request, RenderResponse response) throws Exception {
BeanA bean = new BeanA();
//... init the bean or retrieve from db
List<BeanB> list = new ArrayList<BeanB>();
//... create list of objects
ModelAndView modelAndView = super.handleRenderRequestInternal(request, response);
modelAndView.getModel().put("beans", list);
modelAndView.getModel().put("bean", bean);
return modelAndView ;
}
}
在jsp中,我想使用form.select从给定列表中选择要为BeanA设置的项目,例如:
<form:select path="${bean.bean}" items="${beans}"/>
看起来像这样不起作用。 是否有另一个简单的解决方案?
要在HTML中创建选择标记:
<form:select path="bean" items="${candidates}" itemValue="id" itemLabel="name"/>
提交表单后,该值将作为字符串传递到Spring,然后需要将其转换为所需类型的bean。 Spring为此使用WebDataBinder,并使用PropertyEditors进行到String的转换。 由于您的'id'属性可能已经可序列化为字符串,因此您已经看到其中一半工作了。
您正在寻找的是: http : //static.springsource.org/spring/docs/2.5.6/reference/mvc.html#mvc-ann-webdatabinder
@InitBinder
protected void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(BeanB.class, new PropertyEditorSupport() {
@Override
public void setAsText(String text) {
// some code to load your bean..
// the example here assumes BeanB class knows how to return
// a bean for a specific id (which is an int/Integer) by
// calling the valueOf static method
// eg:
setValue(BeanB.valueOf(Integer.valueOf(text)));
}
});
}
Spring 2.5.6的文档似乎建议@Controller和@InitBinder批注在配置后可以正常工作,您必须针对您的环境进行推断。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.