Original address: The difference between springMVC Model ModelMap and ModelAndView
Recently, I was looking at the code and found that there are different ways to process the returned data in the controller, and I have been using ModelAndView to process data, and I have used other methods sporadically, but I always feel that I don't understand the difference, so I wrote this This blog summarizes:
simply put:
Model is an interface that contains four addAttribute and one merAttribute methods.
ModelMap : Implements the Map interface, including the Map method. The view layer finds the data in the ModelMap through the request.
ModelAndView: is a container that contains ModelMap and view objects. As the name implies, it contains both the model and the view, while the ModelMap just contains information about the model.
Example of ModelAndView, behind the scenes
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; } }
Example of ModelAndView, foreground 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>
Example of ModelMap:
public String testMethod(String someparam,ModelMap model) { // Omit some method processing logic // Place the data into the ModelMap object model, the second parameter can be any java type model.addAttribute("key" ,someparam); ...... // return jump address return "test/test" ; }
Or use the interface directly:
public String toProvinceView(Model model, HttpSession session,) { model.addAttribute("colModel", colModel); model.addAttribute("colNames", colNames); model.addAttribute("buttonName", buttonName); return "statistic/StatisticChart"; }
References:
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