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,
并调用了 Model 的addAttribute方法,以键-值的形式传入参数 "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的用法
每天学习一点点,每天进步一点点。

浙公网安备 33010602011771号