原文地址:https://blog.csdn.net/qq30211478/article/details/78016155

(一)使用ModelAndView类用来存储处理完后的结果数据,以及显示该数据的视图。从名字上看ModelAndView中的Model代表模型,View代表视图,这个名字就很好地解释了该类的作用。业务处理器调用模型层处理完用户请求后,把结果数据存储在该类的model属性中,把要返回的视图信息存储在该类的view属性中,然后让该ModelAndView返回该Spring MVC框架。框架通过调用配置文件中定义的视图解析器,对该对象进行解析,最后把结果数据显示在指定的页面上。

具体作用:

1、返回指定页面

ModelAndView构造方法可以指定返回的页面名称,

也可以通过setViewName()方法跳转到指定的页面 ,

2、返回所需数值

使用addObject()设置需要返回的值,addObject()有几个不同参数的方法,可以默认和指定返回对象的名字。

1、【其源码】:熟悉一个类的用法,最好从其源码入手。

  1. public class ModelAndView {
  2.  
  3. /** View instance or view name String */
  4. private Object view //该属性用来存储返回的视图信息
  5. /** Model Map */
  6. private ModelMap model;//<span style="color: rgb(0, 130, 0); font-family: Consolas, 'Courier New', Courier, mono, serif; line-height: 18px;">该属性用来存储处理后的结果数据</span>
  7.  
  8. /**
  9. * Indicates whether or not this instance has been cleared with a call to {@link #clear()}.
  10. */
  11. private boolean cleared = false;
  12.  
  13. /**
  14. * Default constructor for bean-style usage: populating bean
  15. * properties instead of passing in constructor arguments.
  16. * @see #setView(View)
  17. * @see #setViewName(String)
  18. */
  19. public ModelAndView() {
  20. }
  21.  
  22. /**
  23. * Convenient constructor when there is no model data to expose.
  24. * Can also be used in conjunction with <code>addObject</code>.
  25. * @param viewName name of the View to render, to be resolved
  26. * by the DispatcherServlet's ViewResolver
  27. * @see #addObject
  28. */
  29. public ModelAndView(String viewName) {
  30. this.view = viewName;
  31. }
  32.  
  33. /**
  34. * Convenient constructor when there is no model data to expose.
  35. * Can also be used in conjunction with <code>addObject</code>.
  36. * @param view View object to render
  37. * @see #addObject
  38. */
  39. public ModelAndView(View view) {
  40. this.view = view;
  41. }
  42.  
  43. /**
  44. * Creates new ModelAndView given a view name and a model.
  45. * @param viewName name of the View to render, to be resolved
  46. * by the DispatcherServlet's ViewResolver
  47. * @param model Map of model names (Strings) to model objects
  48. * (Objects). Model entries may not be <code>null</code>, but the
  49. * model Map may be <code>null</code> if there is no model data.
  50. */
  51. public ModelAndView(String viewName, Map<String, ?> model) {
  52. this.view = viewName;
  53. if (model != null) {
  54. getModelMap().addAllAttributes(model);
  55. }
  56. }
  57.  
  58. /**
  59. * Creates new ModelAndView given a View object and a model.
  60. * <emphasis>Note: the supplied model data is copied into the internal
  61. * storage of this class. You should not consider to modify the supplied
  62. * Map after supplying it to this class</emphasis>
  63. * @param view View object to render
  64. * @param model Map of model names (Strings) to model objects
  65. * (Objects). Model entries may not be <code>null</code>, but the
  66. * model Map may be <code>null</code> if there is no model data.
  67. */
  68. public ModelAndView(View view, Map<String, ?> model) {
  69. this.view = view;
  70. if (model != null) {
  71. getModelMap().addAllAttributes(model);
  72. }
  73. }
  74.  
  75. /**
  76. * Convenient constructor to take a single model object.
  77. * @param viewName name of the View to render, to be resolved
  78. * by the DispatcherServlet's ViewResolver
  79. * @param modelName name of the single entry in the model
  80. * @param modelObject the single model object
  81. */
  82. public ModelAndView(String viewName, String modelName, Object modelObject) {
  83. this.view = viewName;
  84. addObject(modelName, modelObject);
  85. }
  86.  
  87. /**
  88. * Convenient constructor to take a single model object.
  89. * @param view View object to render
  90. * @param modelName name of the single entry in the model
  91. * @param modelObject the single model object
  92. */
  93. public ModelAndView(View view, String modelName, Object modelObject) {
  94. this.view = view;
  95. addObject(modelName, modelObject);
  96. }
  97.  
  98. /**
  99. * Set a view name for this ModelAndView, to be resolved by the
  100. * DispatcherServlet via a ViewResolver. Will override any
  101. * pre-existing view name or View.
  102. */
  103. public void setViewName(String viewName) {
  104. this.view = viewName;
  105. }
  106.  
  107. /**
  108. * Return the view name to be resolved by the DispatcherServlet
  109. * via a ViewResolver, or <code>null</code> if we are using a View object.
  110. */
  111. public String getViewName() {
  112. return (this.view instanceof String ? (String) this.view : null);
  113. }
  114.  
  115. /**
  116. * Set a View object for this ModelAndView. Will override any
  117. * pre-existing view name or View.
  118. */
  119. public void setView(View view) {
  120. this.view = view;
  121. }
  122.  
  123. /**
  124. * Return the View object, or <code>null</code> if we are using a view name
  125. * to be resolved by the DispatcherServlet via a ViewResolver.
  126. */
  127. public View getView() {
  128. return (this.view instanceof View ? (View) this.view : null);
  129. }
  130.  
  131. /**
  132. * Indicate whether or not this <code>ModelAndView</code> has a view, either
  133. * as a view name or as a direct {@link View} instance.
  134. */
  135. public boolean hasView() {
  136. return (this.view != null);
  137. }
  138.  
  139. /**
  140. * Return whether we use a view reference, i.e. <code>true</code>
  141. * if the view has been specified via a name to be resolved by the
  142. * DispatcherServlet via a ViewResolver.
  143. */
  144. public boolean isReference() {
  145. return (this.view instanceof String);
  146. }
  147.  
  148. /**
  149. * Return the model map. May return <code>null</code>.
  150. * Called by DispatcherServlet for evaluation of the model.
  151. */
  152. protected Map<String, Object> getModelInternal() {
  153. return this.model;
  154. }
  155.  
  156. /**
  157. * Return the underlying <code>ModelMap</code> instance (never <code>null</code>).
  158. */
  159. public ModelMap getModelMap() {
  160. if (this.model == null) {
  161. this.model = new ModelMap();
  162. }
  163. return this.model;
  164. }
  165.  
  166. /**
  167. * Return the model map. Never returns <code>null</code>.
  168. * To be called by application code for modifying the model.
  169. */
  170. public Map<String, Object> getModel() {
  171. return getModelMap();
  172. }
  173.  
  174. /**
  175. * Add an attribute to the model.
  176. * @param attributeName name of the object to add to the model
  177. * @param attributeValue object to add to the model (never <code>null</code>)
  178. * @see ModelMap#addAttribute(String, Object)
  179. * @see #getModelMap()
  180. */
  181. public ModelAndView addObject(String attributeName, Object attributeValue) {
  182. getModelMap().addAttribute(attributeName, attributeValue);
  183. return this;
  184. }
  185.  
  186. /**
  187. * Add an attribute to the model using parameter name generation.
  188. * @param attributeValue the object to add to the model (never <code>null</code>)
  189. * @see ModelMap#addAttribute(Object)
  190. * @see #getModelMap()
  191. */
  192. public ModelAndView addObject(Object attributeValue) {
  193. getModelMap().addAttribute(attributeValue);
  194. return this;
  195. }
  196.  
  197. /**
  198. * Add all attributes contained in the provided Map to the model.
  199. * @param modelMap a Map of attributeName -> attributeValue pairs
  200. * @see ModelMap#addAllAttributes(Map)
  201. * @see #getModelMap()
  202. */
  203. public ModelAndView addAllObjects(Map<String, ?> modelMap) {
  204. getModelMap().addAllAttributes(modelMap);
  205. return this;
  206. }
  207.  
  208. /**
  209. * Clear the state of this ModelAndView object.
  210. * The object will be empty afterwards.
  211. * <p>Can be used to suppress rendering of a given ModelAndView object
  212. * in the <code>postHandle</code> method of a HandlerInterceptor.
  213. * @see #isEmpty()
  214. * @see HandlerInterceptor#postHandle
  215. */
  216. public void clear() {
  217. this.view = null;
  218. this.model = null;
  219. this.cleared = true;
  220. }
  221.  
  222. /**
  223. * Return whether this ModelAndView object is empty,
  224. * i.e. whether it does not hold any view and does not contain a model.
  225. */
  226. public boolean isEmpty() {
  227. return (this.view == null && CollectionUtils.isEmpty(this.model));
  228. }
  229.  
  230. /**
  231. * Return whether this ModelAndView object is empty as a result of a call to {@link #clear}
  232. * i.e. whether it does not hold any view and does not contain a model.
  233. * <p>Returns <code>false</code> if any additional state was added to the instance
  234. * <strong>after</strong> the call to {@link #clear}.
  235. * @see #clear()
  236. */
  237. public boolean wasCleared() {
  238. return (this.cleared && isEmpty());
  239. }
  240.  
  241. /**
  242. * Return diagnostic information about this model and view.
  243. */
  244. @Override
  245. public String toString() {
  246. StringBuilder sb = new StringBuilder("ModelAndView: ");
  247. if (isReference()) {
  248. sb.append("reference to view with name '").append(this.view).append("'");
  249. }
  250. else {
  251. sb.append("materialized View is [").append(this.view).append(']');
  252. }
  253. sb.append("; model is ").append(this.model);
  254. return sb.toString();
  255. }

在源码中有7个构造函数,如何用?是一个重点。

构造ModelAndView对象当控制器处理完请求时,通常会将包含视图名称或视图对象以及一些模型属性的ModelAndView对象返回到DispatcherServlet。

因此,经常需要在控制器中构造ModelAndView对象。

ModelAndView类提供了几个重载的构造器和一些方便的方法,让你可以根据自己的喜好来构造ModelAndView对象。这些构造器和方法以类似的方式支持视图名称和视图对象。

通过ModelAndView构造方法可以指定返回的页面名称,也可以通过setViewName()方法跳转到指定的页面 , 使用addObject()设置需要返回的值,addObject()有几个不同参数的方法,可以默认和指定返回对象的名字

(1)当你只有一个模型属性要返回时,可以在构造器中指定该属性来构造ModelAndView对象:

  1. package com.apress.springrecipes.court.web;
  2. ...
  3. import org.springframework.web.servlet.ModelAndView;
  4. import org.springframework.web.servlet.mvc.AbstractController;
  5. public class WelcomeController extends AbstractController{
  6. public ModelAndView handleRequestInternal(HttpServletRequest request,
  7. HttpServletResponse response)throws Exception{
  8. Date today = new Date();
  9. return new ModelAndView("welcome","today",today);
  10. }
  11. }

(2)如果有不止一个属性要返回,可以先将它们传递到一个Map中再来构造ModelAndView对象。

  1. package com.apress.springrecipes.court.web;
  2. ...
  3. import org.springframework.web.servlet.ModelAndView;
  4. import org. springframework.web.servlet.mvc.AbstractController;
  5. public class ReservationQueryController extends AbstractController{
  6. ...
  7. public ModelAndView handleRequestInternal(HttpServletRequest request,
  8. HttpServletResponse response)throws Exception{
  9. ...
  10. Map<String,Object> model = new HashMap<String,Object>();
  11. if(courtName != null){
  12. model.put("courtName",courtName);
  13. model.put("reservations",reservationService.query(courtName));
  14. }
  15. return new ModelAndView("reservationQuery",model);
  16. }
  17. }

Spring也提供了ModelMap,这是java.util.Map实现,可以根据模型属性的具体类型自动生成模型属性的名称。

  1. package com.apress.springrecipes.court.web;
  2. ...
  3. import org.springframework.ui.ModelMap;
  4. import org.springframework.web.servlet.ModelAndView;
  5. import org.springframework.web.servlet.mvc.AbstractController;
  6. public class ReservationQueryController extends AbstractController{
  7. ...
  8. public ModelAndView handleRequestInternal(HttpServletRequest request,
  9. HttpServletResponse response)throws Exception{
  10. ...
  11. ModelMap model = new ModelMap();
  12. if(courtName != null){
  13. model.addAttribute("courtName",courtName);
  14. model.addAttribute("reservations",reservationService.query(courtName));
  15. }
  16. return new ModelAndView("reservationQuery",model);
  17. }
  18. }

这里,我又想多说一句:ModelMap对象主要用于传递控制方法处理数据到结果页面,

也就是说我们把结果页面上需要的数据放到ModelMap对象中即可,他的作用类似于request对象的setAttribute方法的作用,用来在一个请求过程中传递处理的数据

通过以下方法向页面传递参数:

  1. addAttribute(String key,Object value); //modelMap的方法

在页面上可以通过el变量方式${key}或者bboss的一系列数据展示标签获取并展示modelmap中的数据。

modelmap本身不能设置页面跳转的url地址别名或者物理跳转地址,那么我们可以通过控制器方法的返回值设置跳转url地址别名或者物理跳转地址。 比如:

  1. public String xxxxmethod(String someparam,ModelMap model)
  2. {
  3. //省略方法处理逻辑若干
  4. //将数据放置到ModelMap对象model中,第二个参数可以是任何java类型
  5. model.addAttribute("key",someparam);
  6. ......
  7. //返回跳转地址
  8. return "path:handleok";
  9. }

在这些构造函数中最简单的ModelAndView是持有View的名称返回,之后View名称被view resolver,也就是实作org.springframework.web.servlet.View接口的实例解析,

例如: InternalResourceView或JstlView等等:ModelAndView(String viewName);

如果您要返回Model对象,则可以使用Map来收集这些Model对象,然后设定给ModelAndView,使用下面这个版本:

  1. ModelAndViewModelAndView(String viewName, Map model),Map对象中设定好keyvalue值,之后可以在视图中取出

如果您只是要返回一个Model对象,则可以使用下面这个 ModelAndView版本:

  1. ModelAndView(String viewName, String modelName, Object modelObject),其中modelName,您可以在视图中取出Model并显示

ModelAndView类别提供实作View接口的对象来作View的参数:

  1. ModelAndView(View view)
  2.  
  3. ModelAndView(View view, Map model)
  4.  
  5. ModelAndView(View view, String modelName, Object modelObject)

2【方法使用】:给ModelAndView实例设置view的方法有两个:setViewName(String viewName) 和 setView(View view)。

前者是使用viewName,后者是使用预先构造好的View对象。其中前者比较常用。事实上View是一个接口,而不是一个可以构造的具体类,我们只能通过其他途径来获取View的实例。对于viewName,它既可以是jsp的名字,也可以是tiles定义的名字,取决于使用的ViewNameResolver如何理解这个view name。如何获取View的实例以后再研究。

而对应如何给ModelAndView实例设置model则比较复杂。有三个方法可以使用:

  1. addObject(Object modelObject);
  2. addObject(String modelName, Object modelObject);
  3. addAllObjects(Map modelMap);

3【作用简介】:

ModelAndView对象有两个作用: 
作用一: 设置转向地址,如下所示(这也是ModelAndView和ModelMap的主要区别

  1. ModelAndView view = new ModelAndView("path:ok");

作用二 :用于传递控制方法处理结果数据到结果页面,也就是说我们把需要在结果页面上需要的数据放到ModelAndView对象中即可

他的作用类似于request对象的setAttribute方法的作用,用来在一个请求过程中传递处理的数据。通过以下方法向页面传递参数:

  1. addObject(String key,Object value);

SpringMVC之ModelAndView的用法(转)的更多相关文章

  1. SpringMVC之ModelAndView的用法

    https://blog.csdn.net/qq30211478/article/details/78016155

  2. SpringMVC之ModelAndView的简单使用

    可以使用ModelAndView来跳转页面和传值,具体用法如下: 构造方法的参数是要跳转的页面! 通过 ModelAndView 的对象的 AddObject(K,V)方法,可以传入数据! 获得mod ...

  3. SpringMVC中的session用法及细节记录

    前言 初学SpringMVC,最近在给公司做的系统做登录方面,需要用到session. 在网上找了不少资料,大致提了2点session保存方式: 1.javaWeb工程通用的HttpSession 2 ...

  4. springMVC中ModelAndView学写笔记

    api介绍: 构造函数摘要 ModelAndView()           bean样式用法的默认构造函数:填充bean属性,而不是传递构造函数参数. ModelAndView(Object vie ...

  5. SpringMVC使用ModelAndView进行重定向

    1.Servlet重定向forward与redirect: 使用servlet重定向有两种方式,一种是forward,另一种就是redirect.forward是服务器内部重定向,客户端并不知道服务器 ...

  6. springmvc相关配置和用法

    目录如下: 一.spring mvc 核心类与接口 二.spring mvc 核心流程图 三.spring mvc DispatcherServlet说明 四.spring mvc 父子上下文的说明 ...

  7. SpringMVC学习 -- ModelAndView , Model , ModelMap , Map 及 @SessionAttributes 的使用

    输出模型数据: ModelAndView:处理方法返回值类型为 ModelAndView 时 , 其中包含视图和模型信息.方法体即可通过该对象添加模型数据 , 即 SpringMVC 会把 Model ...

  8. SpringMvc中ModelAndView模型的应用

    /** * 目标方法的返回值可以是 ModelAndView 类型. * 其中可以包含视图和模型信息 * SpringMVC 会把 ModelAndView 的 model 中数据放入到 reques ...

  9. SpringMVC中ModelAndView的两个jar包引起的思考servlet和portlet

    在使用ModelAndView时,需要去导包,但是有两个包. 检查前台form表单提交的也正确,后台这也没有问题. 后来发现竟然时导包导错误了. 到此,如果是因为到错包问题,应该就解决了. 但是,深入 ...

随机推荐

  1. Android之判断时间是否为今天

    字符串:      sdate =  2013-07-16 13:35:02 /** * 判断给定字符串时间是否为今日 * @param sdate * @return boolean */ publ ...

  2. Ladda 应用提交表单的时候显示loading载入中 包含不同位置,不同效果

    Ladda 应用提交表单的时候显示loading载入中 包含不同位置,不同效果 不同大小.位置,效果,进度条等 演示 XML/HTML Code <article class="exa ...

  3. bashrc和profile的用途和区别

    使用终端登录Linux操作系统的控制台后,会出现一个提示符号(例如:#或~),在这个提示符号之后可以输入命令,Linux根据输入的命令会做回应,这一连串的动作是由一个所谓的Shell来做处理. She ...

  4. 端口复用技术简单了解;重用端口;socket复用端口

    端口复用相关点 多个应用复用端口,只有最后一个绑定的socket可以接受数据,所有socket都可以发送数据 使用端口复用技术时,所有的socket都开启端口复用,才可以实现端口复用 黑客技术,使用标 ...

  5. Dijkstra算法求最短路径(java)(转)

    原文链接:Dijkstra算法求最短路径(java) 任务描述:在一个无向图中,获取起始节点到所有其他节点的最短路径描述 Dijkstra(迪杰斯特拉)算法是典型的最短路径路由算法,用于计算一个节点到 ...

  6. Spark向HDFS中存储数据

    程序如下: import org.apache.spark.sql.Row; import org.apache.spark.SparkConf; import org.apache.spark.ap ...

  7. CenoOS下如何对mysql编码进行配置

    1 修改/etc/mysql/my.cnf配置文件 增加default-character-set=utf8 配置文件如下 [client] port = 3306 socket = /var/run ...

  8. Visual Studio Code 构建C/C++开发环境

    转自: https://blog.csdn.net/lidong_12664196/article/details/68928136#visual-sutdio-code%E4%BB%A5%E5%8F ...

  9. GoLang中面向对象的三大特性

    有过 JAVA 语言学习经历的朋友都知道,面向对象主要包括了三个基本特征:封装.继承和多态.封装,就是指运行的数据和函数绑定在一起,JAVA 中主要是通过 super 指针来完成的:继承,就是指 cl ...

  10. 在不重装系统的情况下撤底删除oracle数据库及oralce的相关软件

    先从控制面板删除oracle的相关应用及数据库, 删除系统变量 ORACLE_OEM_CLASSPATH=%JAVA_HOME%\lib\ext\access-bridge-64.jar;%JAVA_ ...