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


  • 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){...}

  • 一個例子:
    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;
}


免責聲明!

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



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