Spring MVC 向页面传值-Map、Model、ModelMap、ModelAndView

时间:2021-11-24 00:40:14
  • Spring MVC 向页面传值,有4种方式:

    ModelAndView

    Map

    Model

    ModelMap

  • 使用后面3种方式,都是在方法参数中,指定一个该类型的参数。

  • Model

    Model 是一个接口, 其实现类为ExtendedModelMap,继承了ModelMap类。

public class ExtendedModelMap extends ModelMap implements Model
  • ModelMap

    ModelMap的声明格式:
public class ModelMap extends LinkedHashMap<String, Object>
  • ModelMap或者Model通过addAttribute方法向页面传递参数,其中addAttribute方法参数有多种方式:
public ModelMap addAttribute(String attributeName, Object attributeValue){...}
public ModelMap addAttribute(Object attributeValue){...}
public ModelMap addAllAttributes(Collection<?> attributeValues) {...}
public ModelMap addAllAttributes(Map<String, ?> attributes){...}

Spring MVC 向页面传值-Map、Model、ModelMap、ModelAndView

  • 一个例子:

    Java代码:
@RequestMapping("/test")
public String test(Map<String,Object> map,Model model,ModelMap modelMap){
  map.put("names", Arrays.asList("john","tom","jeff"));
  model.addAttribute("time", new Date());
  modelMap.addAttribute("city", "beijing");
  modelMap.put("gender", "male");
  return "hello";
}

jsp 页面:

1、time:${requestScope.time}<br/>
2、names:${requestScope.names }<br/>
3、city:${requestScope.city }<br/>
4、gender:${requestScope.gender }

结果:

1、time:Sun Mar 08 16:35:58 CST 2017
2、names:[john, tom, jeff]
3、city:beijing
4、gender:male
  • ModelAndView 例子:
@RequestMapping(value = "/mergeModel")
public ModelAndView mergeModel(Model model) {
  model.addAttribute("a", "a"); //① 添加模型数据
  ModelAndView mv = new ModelAndView("success");
  mv.addObject("a", "update"); //② 在视图渲染之前更新③处同名模型数据
  model.addAttribute("a", "new"); //③ 修改①处同名模型数据
  //视图页面的a将显示为"update" 而不是"new"
  return mv;
}