springMVC Model ModelMap 和 ModelAndView的区别

近来在看代码,发现controller里有不同的处理返回数据的方式,而自己一直在用ModelAndView在处理数据,对于其他的方式也零星用过,但是总感觉不明白其中的区别,也就写了这篇博客总结一下:

简单来说:

Model是包含四个addAttribute 和一个  merAttribute方法的接口。

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="http://java.sun.com/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";

参考资料:

http://error.news/question/231833/what-are-the-differences-between-model-modelmap-and-modelandview/

http://stackoverflow.com/questions/3344627/whats-the-difference-between-modelandview-and-modelmap

http://www.concretepage.com/spring/spring-mvc/spring-mvc-form-handling-example

关注我,获取400个的赚钱金点子,轻松开启副业生涯

  • 5
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值