前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >SpringMVC之ModelAndView的用法「建议收藏」

SpringMVC之ModelAndView的用法「建议收藏」

作者头像
全栈程序员站长
发布2022-09-09 11:30:22
2.1K0
发布2022-09-09 11:30:22
举报
文章被收录于专栏:全栈程序员必看

大家好,又见面了,我是你们的朋友全栈君。

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

具体作用:

1、返回指定页面

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

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

2、返回所需数值

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

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

[java] view plain copy

  1. public class ModelAndView {
  2. /** View instance or view name String */
  3. private Object view;//<span style=”color: rgb(0, 130, 0); font-family: Consolas, ‘Courier New’, Courier, mono, serif; line-height: 18px;”>该属性用来存储返回的视图信息</span>

[java] view plain copy

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

在源码中有7个构造函数,如何用?是一个重点。构造ModelAndView对象当控制器处理完请求时,通常会将包含视图名称或视图对象以及一些模型属性的ModelAndView对象返回到DispatcherServlet。因此,经常需要在控制器中构造ModelAndView对象。ModelAndView类提供了几个重载的构造器和一些方便的方法,让你可以根据自己的喜好来构造ModelAndView对象。这些构造器和方法以类似的方式支持视图名称和视图对象。通过ModelAndView构造方法可以指定返回的页面名称,也可以通过setViewName()方法跳转到指定的页面 , 使用addObject()设置需要返回的值,addObject()有几个不同参数的方法,可以默认和指定返回对象的名字。

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

[java] view plain copy

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

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

[java] view plain copy

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

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

[java] view plain copy

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

这里,我又想多说一句:ModelMap对象主要用于传递控制方法处理数据到结果页面,也就是说我们把结果页面上需要的数据放到ModelMap对象中即可,他的作用类似于request对象的setAttribute方法的作用,用来在一个请求过程中传递处理的数据。通过以下方法向页面传递参数:

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

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

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

[java] view plain copy

  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,使用下面这个版本的 ModelAndView:ModelAndView(String viewName, Map model),Map对象中设定好key与value值,之后可以在视图中取出,如果您只是要返回一个Model对象,则可以使用下面这个 ModelAndView版本:ModelAndView(String viewName, String modelName, Object modelObject),其中modelName,您可以在视图中取出Model并显示。

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

ModelAndView(View view)

ModelAndView(View view, Map model)

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则比较复杂。有三个方法可以使用: addObject(Object modelObject);

addObject(String modelName, Object modelObject); addAllObjects(Map modelMap);

3【作用简介】:

ModelAndView对象有两个作用: 作用一 设置转向地址,如下所示(这也是ModelAndView和ModelMap的主要区别) ModelAndView view = new ModelAndView(“path:ok”);

作用二 用于传递控制方法处理结果数据到结果页面,也就是说我们把需要在结果页面上需要的数据放到ModelAndView对象中即可,他的作用类似于request对象的setAttribute方法的作用,用来在一个请求过程中传递处理的数据。通过以下方法向页面传递参数: addObject(String key,Object value);

知识分享不易,望您支持,只为更好!

知识分享不易,望您支持,只为更好

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/160990.html原文链接:https://javaforall.cn

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
数据保险箱
数据保险箱(Cloud Data Coffer Service,CDCS)为您提供更高安全系数的企业核心数据存储服务。您可以通过自定义过期天数的方法删除数据,避免误删带来的损害,还可以将数据跨地域存储,防止一些不可抗因素导致的数据丢失。数据保险箱支持通过控制台、API 等多样化方式快速简单接入,实现海量数据的存储管理。您可以使用数据保险箱对文件数据进行上传、下载,最终实现数据的安全存储和提取。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档