2010-02-17 65 views
0

有沒有一種方法可以使用spring的form.select綁定其他類型bean的bean屬性。 例子:Spring自動綁定下拉列表的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; 
    } 
} 

因爲我想送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}"/> 

看起來它不能像這樣工作。有沒有另一個簡單的解決方案呢?

回答

5

要創建HTML中的選擇標記:

<form:select path="bean" items="${candidates}" itemValue="id" itemLabel="name"/> 

當表單提交,該值將被傳遞到Spring爲字符串,然後將需要被轉換成所需類型的豆。 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註釋工作,如果配置,你必須推斷爲您的環境。

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

+0

謝謝,這看起來是正確的答案,雖然我沒有測試它。我將UI屬性從示例中簡化爲簡單。 – Robert 2010-02-17 14:40:54

+1

我試過這個: 它不起作用。它的工作原理是顯示數值,但不能自動插入bean。有趣的是,當添加這行時,控制器中的onSubmitAction()甚至不會被調用(不會拋出異常)。 我認爲返回的值是一個字符串,它試圖對BeanB進行強制轉換失敗。任何其他想法? – Robert 2010-02-26 14:20:20

+0

您可能需要爲WebDataBinder配置一個PropertyEditor,我會更新我的答案以尋找其他可能的東西 – ptomli 2010-02-27 13:26:53