簡單來說:
ModelMap :實現了Map接口,包含Map方法。視圖層通過request找到ModelMap中的數據。
ModelAndView:是包含ModelMap 和視圖對象的容器。正如名字暗示的壹樣既包含模型也包含視圖,而ModelMap只是包含模型的信息。
ModelAndView的例子,臺後
public?class?CarListController?implements?Controller?{?public?ModelAndView?handleRequest(HttpServletRequest?arg0,?
HttpServletResponse?arg1)?throws?Exception?{?
CarManager?carManager?=?new?CarManager();?
ModelAndView?modelAndView?=?new?ModelAndView("carList");?
modelAndView.addObject("carList",?carManager.getCarList());?
return?modelAndView;?
}?
}
ModelAndView的例子,前臺view
<%@?taglib?prefix="c"?uri="/jsp/jstl/core"?%>?<html>?
<body>?
<h1>Car?List</h1>?
<c:forEach?items="${carList}"?var="car">?
${car.brand.name}?${car.model}:?${car.price}?
<br?/>?
</c:forEach>?
</body>?<html>
ModelMap的例子:
public?String?testMethod(String?someparam,ModelMap?model)?{?
//省略方法處理邏輯若幹? //將數據放置到ModelMap對象model中,第二個參數可以是任何java類型? model.addAttribute("key",someparam);? ......?//返回跳轉地址? return?"test/test";?}
或者直接使用接口:
public?String?toProvinceView(Model?model,?HttpSession?session)?{?
model.addAttribute("colModel",?colModel);?
model.addAttribute("colNames",?colNames);?
model.addAttribute("buttonName",?buttonName);?
return?"statistic/StatisticChart";?
}