天天看點

Spring MVC 向頁面傳值-Map、Model、ModelMap、ModelAndView

  • Spring MVC 向頁面傳值,有4種方式:

    ModelAndView

    Map

    Model

    ModelMap

  • 使用後面3種方式,都是在方法參數中,指定一個該類型的參數。
  • Model 是一個接口, 其實作類為ExtendedModelMap,繼承了ModelMap類。
public class ExtendedModelMap extends ModelMap implements Model
           
  • 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){...}
           
  • 一個例子:

    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";
}
           
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;
}
           

繼續閱讀