簡體   English   中英

Spring MVC是否使用setter方法設置ModelAttribute對象的屬性?

[英]Is Spring MVC using setter methods to set the properties of ModelAttribute objects?

Spring MVC是否使用getter和setter來設置ModelAttribute對象的值? 你能不能引用我這樣說的消息來源。 如果沒有,我們如何強制Spring MVC使用setter來設置模型對象的屬性?

謝謝。

我不知道這是否真的回答了這個問題,但我在文檔中找到了這個引用:

命令或表單對象將請求參數綁定到bean屬性(通過setter)或直接綁定到字段,具有可自定義的類型轉換,具體取決於@InitBinder方法和/或HandlerAdapter配置。 ... ModelAttribute注釋可用於方法參數,以自定義使用的模型屬性名稱。

這似乎意味着如果可用的話,將使用setter,直接更新字段作為后備。

但是如果你想要一個明確的答案,請查看源代碼。

我也遇到過這個問題,情況如下:

代碼片段:

Product.java

public class Product {

    private String name;
    private String imageStr;
    private List<ProdutImage> productImageList;

    public String getName() {
        return this.name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List<ProductImage> getProductImageList() {
        return this.productImageList;
    }

    public void setProductImageList(List<ProductImage> productImageList) {
        this.productImageList = productImageList;
        if (productImageList != null) {
            this.imageStr = [...]// convert list to json string
        }
    }

}

它沒有直接設置“imageStr”,但基於圖像列表字段,jsp頁面喜歡:

 <form>
      <input type="text" name="product.name"/>
      <input type="text" name="product.productImageList[0]"/>
      <input type="text" name="product.productImageList[1]"/>
      <input type="text" name="product.productImageList[2]"/>
   </form>

提交表單時,“name”和“productImageList”都可以成功填充,有一點不同,我把斷點都放在“setName”和“setProductImageList”中,我們可以發現“setName”被調用,但是不是“setProductImageList”,因為這樣,“imageStr”為null。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM