Spring MVC 向页面传值 Map、Model和ModelMap

除了使用ModelAndView方式外还可以使用Map、Model和ModelMap来向前台页面传值

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

  @RequestMapping("/test")
  public String test(Map<String,Object> map,Model model,ModelMap modelMap){
      map.put("names", Arrays.asList("caoyc","zhh","cjx"));
      model.addAttribute("time", new Date());
      modelMap.addAttribute("city", "ChengDu");
      modelMap.put("gender", "male");
      mv.addObject("name", "张三");
      return "hello";
  }
  JSP页面
    1、time:${requestScope.time}  <br/>   
    2、names:${requestScope.names } <br/>
    3、city:${requestScope.city }   <br/>
    4、gender:${requestScope.gender }



model.addAttribute("cusType", session.getAttribute("cusType")); //从session获取放到model域中, 并清楚session的值

session.removeAttribute("cusType");


除了使用ModelAndView方式外 (有局限性, 必须返回ModelAndView )。

@RequestMapping(value = "login")
public ModelAndView login(){
   ModelAndView mav = new ModelAndView();
   mav.setViewName("welcome"); //跳转到 welcome.jsp
   mav.addObject("msg", "hello kitty");
   return mav;
}

猜你喜欢

转载自blog.csdn.net/qq_29883183/article/details/80340842