Spring MVC 中 Model 的用法


Model 的作用

Model 對象負責在控制器和展現數據的視圖之間傳遞數據。

實際上,放到 Model 屬性中的數據將會復制到 Servlet Response 的屬性中,這樣視圖就能在這里找到它們了。

從廣義上來說,Model 指的是 MVC 中的 M,即 Model(模型)。從狹義上講,Model 就是個 key-value 集合。

Model 的繼承關系

Model 是一個接口,它的實現類為 ExtendedModelMap,繼承 ModelMap 類

public class ExtendedModelMap extends ModelMap implements Model

示例

package com.example.tacocloud.controller;

import com.example.tacocloud.bean.Order;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@Slf4j
@RequestMapping("/orders")
public class OrderController {
    /**
     * orderForm() 方法本身非常簡單,
     * 只是返回了一個名為 orderForm 的邏輯視圖名。
     */
    @GetMapping("/current")
    public String orderForm(Model model){
        model.addAttribute("order", new Order());
        return "orderForm";
    }
}

上面這段代碼中,方法 orderForm的參數是 Model model ,這表明使用了 Model,

並調用了 ModeladdAttribute方法,以鍵-值的形式傳入參數 "order", new Order()

最后,return "orderForm";表示返回名為orderForm的邏輯視圖,也就意味着,我們要在 \resources\templates目錄下,建立對應的 orderForm.html 文件

Model 源碼分析

Model接口的源碼如下:

public interface Model {
    Model addAttribute(String var1, @Nullable Object var2);

    Model addAttribute(Object var1);

    Model addAllAttributes(Collection<?> var1);

    Model addAllAttributes(Map<String, ?> var1);

    Model mergeAttributes(Map<String, ?> var1);

    boolean containsAttribute(String var1);

    @Nullable
    Object getAttribute(String var1);

    Map<String, Object> asMap();
}

可以看出,使用 Model,主要就是調用它的addAttribute()方法,或者addAllAttributes()方法。

addAttribute()方法,就是傳入單個的鍵值對

addAllAttributes()方法,就是以 集合或者字典的形式,傳入一組鍵值對。

參考資料

1、Spring中Model詳解
2、Spring Boot教程(9) – Model的用法

每天學習一點點,每天進步一點點。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM