Spring自动绑定bean属性的下拉列表

0 java spring spring-mvc

有没有办法使用spring的form.select绑定另一种bean的bean属性.例:

我有一个bean需要在视图中使用名为BeanB的属性进行更新:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

对于视图,我想发送一个使用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 ;
}
}
Run Code Online (Sandbox Code Playgroud)

在jsp中我想使用form.select从给定列表中选择我想要为BeanA设置的项,如:

<form:select path="${bean.bean}" items="${beans}"/>
Run Code Online (Sandbox Code Playgroud)

看起来它不像这样工作.还有另一个简单的解决方案吗?

pto*_*mli 5

要在HTML中创建选择标记:

<form:select path="bean" items="${candidates}" itemValue="id" itemLabel="name"/>
Run Code Online (Sandbox Code Playgroud)

提交表单时,该值将作为String传递给Spring,然后需要将其转换为所需类型的bean.Spring使用WebDataBinder,使用PropertyEditors进行String转换.由于您的'id'属性可能已经可以序列化为String,因此您已经看到了其中一半的工作.

您正在寻找: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)));
        }
    });
}
Run Code Online (Sandbox Code Playgroud)

Spring 2.5.6的文档似乎暗示@Controller和@InitBinder注释在配置时有效,你必须为你的环境推断.

@see http://static.springsource.org/spring/docs/2.5.6/api/index.html?org/springframework/web/bind/WebDataBinder.html