SpringMVC之ModelAndView的用法

ModelAndView: 這個就是一個頁面控制器,如獲取登錄頁面的參數,跳轉到首頁,完成登錄操作 也可以指定獲取的參數類型 1、返回指定頁面 ModelAndView構造方法可以指定返回的頁面名稱, 也可以通過setViewName()方法跳轉到指定的頁面

2、返回所需數值
使用addObject()設置需要返回的值,addObject()有幾個不同參數的方法,可以默認和指定返回對象的名字。

3、ModelAndView構造方法可以指定返回的頁面名稱,也可以通過setViewName()方法跳轉到指定的頁面 , 使用addObject()設置需要返回的值,addObject()有幾個不同參數的方法,可以默認和指定返回對象的名字。

(一)使用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.   
  3.     /** View instance or view name String */  
  4.     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. /** 
  5.  * Indicates whether or not this instance has been cleared with a call to {@link #clear()}. 
  6.  */  
  7. private boolean cleared = false;  
  8.   
  9.   
  10. /** 
  11.  * Default constructor for bean-style usage: populating bean 
  12.  * properties instead of passing in constructor arguments. 
  13.  * @see #setView(View) 
  14.  * @see #setViewName(String) 
  15.  */  
  16. public ModelAndView() {  
  17. }  
  18.   
  19. /** 
  20.  * Convenient constructor when there is no model data to expose. 
  21.  * Can also be used in conjunction with <code>addObject</code>. 
  22.  * @param viewName name of the View to render, to be resolved 
  23.  * by the DispatcherServlet's ViewResolver 
  24.  * @see #addObject 
  25.  */  
  26. public ModelAndView(String viewName) {  
  27.     this.view = viewName;  
  28. }  
  29.   
  30. /** 
  31.  * Convenient constructor when there is no model data to expose. 
  32.  * Can also be used in conjunction with <code>addObject</code>. 
  33.  * @param view View object to render 
  34.  * @see #addObject 
  35.  */  
  36. public ModelAndView(View view) {  
  37.     this.view = view;  
  38. }  
  39.   
  40. /** 
  41.  * Creates new ModelAndView given a view name and a model. 
  42.  * @param viewName name of the View to render, to be resolved 
  43.  * by the DispatcherServlet's ViewResolver 
  44.  * @param model Map of model names (Strings) to model objects 
  45.  * (Objects). Model entries may not be <code>null</code>, but the 
  46.  * model Map may be <code>null</code> if there is no model data. 
  47.  */  
  48. public ModelAndView(String viewName, Map<String, ?> model) {  
  49.     this.view = viewName;  
  50.     if (model != ) {  
  51.         getModelMap().addAllAttributes(model);  
  52.     }  
  53. }  
  54.   
  55. /** 
  56.  * Creates new ModelAndView given a View object and a model. 
  57.  * <emphasis>Note: the supplied model data is copied into the internal 
  58.  * storage of this class. You should not consider to modify the supplied 
  59.  * Map after supplying it to this class</emphasis> 
  60.  * @param view View object to render 
  61.  * @param model Map of model names (Strings) to model objects 
  62.  * (Objects). Model entries may not be <code>null</code>, but the 
  63.  * model Map may be <code>null</code> if there is no model data. 
  64.  */  
  65. public ModelAndView(View view, Map<String, ?> model) {  
  66.     this.view = view;  
  67.     if (model != ) {  
  68.         getModelMap().addAllAttributes(model);  
  69.     }  
  70. }  
  71.   
  72. /** 
  73.  * Convenient constructor to take a single model object. 
  74.  * @param viewName name of the View to render, to be resolved 
  75.  * by the DispatcherServlet's ViewResolver 
  76.  * @param modelName name of the single entry in the model 
  77.  * @param modelObject the single model object 
  78.  */  
  79. public ModelAndView(String viewName, String modelName, Object modelObject) {  
  80.     this.view = viewName;  
  81.     addObject(modelName, modelObject);  
  82. }  
  83.   
  84. /** 
  85.  * Convenient constructor to take a single model object. 
  86.  * @param view View object to render 
  87.  * @param modelName name of the single entry in the model 
  88.  * @param modelObject the single model object 
  89.  */  
  90. public ModelAndView(View view, String modelName, Object modelObject) {  
  91.     this.view = view;  
  92.     addObject(modelName, modelObject);  
  93. }  
  94.   
  95.   
  96. /** 
  97.  * Set a view name for this ModelAndView, to be resolved by the 
  98.  * DispatcherServlet via a ViewResolver. Will override any 
  99.  * pre-existing view name or View. 
  100.  */  
  101. public void setViewName(String viewName) {  
  102.     this.view = viewName;  
  103. }  
  104.   
  105. /** 
  106.  * Return the view name to be resolved by the DispatcherServlet 
  107.  * via a ViewResolver, or <code>null</code> if we are using a View object. 
  108.  */  
  109. public String getViewName() {  
  110.     return (this.view instanceof String ? (String) this.view : );  
  111. }  
  112.   
  113. /** 
  114.  * Set a View object for this ModelAndView. Will override any 
  115.  * pre-existing view name or View. 
  116.  */  
  117. public void setView(View view) {  
  118.     this.view = view;  
  119. }  
  120.   
  121. /** 
  122.  * Return the View object, or <code>null</code> if we are using a view name 
  123.  * to be resolved by the DispatcherServlet via a ViewResolver. 
  124.  */  
  125. public View getView() {  
  126.     return (this.view instanceof View ? (View) this.view : );  
  127. }  
  128.   
  129. /** 
  130.  * Indicate whether or not this <code>ModelAndView</code> has a view, either 
  131.  * as a view name or as a direct {@link View} instance. 
  132.  */  
  133. public boolean hasView() {  
  134.     return (this.view != );  
  135. }  
  136.   
  137. /** 
  138.  * Return whether we use a view reference, i.e. <code>true</code> 
  139.  * if the view has been specified via a name to be resolved by the 
  140.  * DispatcherServlet via a ViewResolver. 
  141.  */  
  142. public boolean isReference() {  
  143.     return (this.view instanceof String);  
  144. }  
  145.   
  146. /** 
  147.  * Return the model map. May return <code>null</code>. 
  148.  * Called by DispatcherServlet for evaluation of the model. 
  149.  */  
  150. protected Map<String, Object> getModelInternal() {  
  151.     return this.model;  
  152. }  
  153.   
  154. /** 
  155.  * Return the underlying <code>ModelMap</code> instance (never <code>null</code>). 
  156.  */  
  157. public ModelMap getModelMap() {  
  158.     if (this.model == ) {  
  159.         this.model = new ModelMap();  
  160.     }  
  161.     return this.model;  
  162. }  
  163.   
  164. /** 
  165.  * Return the model map. Never returns <code>null</code>. 
  166.  * To be called by application code for modifying the model. 
  167.  */  
  168. public Map<String, Object> getModel() {  
  169.     return getModelMap();  
  170. }  
  171.   
  172.   
  173. /** 
  174.  * Add an attribute to the model. 
  175.  * @param attributeName name of the object to add to the model 
  176.  * @param attributeValue object to add to the model (never <code>null</code>) 
  177.  * @see ModelMap#addAttribute(String, Object) 
  178.  * @see #getModelMap() 
  179.  */  
  180. public ModelAndView addObject(String attributeName, Object attributeValue) {  
  181.     getModelMap().addAttribute(attributeName, attributeValue);  
  182.     return this;  
  183. }  
  184.   
  185. /** 
  186.  * Add an attribute to the model using parameter name generation. 
  187.  * @param attributeValue the object to add to the model (never <code>null</code>) 
  188.  * @see ModelMap#addAttribute(Object) 
  189.  * @see #getModelMap() 
  190.  */  
  191. public ModelAndView addObject(Object attributeValue) {  
  192.     getModelMap().addAttribute(attributeValue);  
  193.     return this;  
  194. }  
  195.   
  196. /** 
  197.  * Add all attributes contained in the provided Map to the model. 
  198.  * @param modelMap a Map of attributeName -> attributeValue pairs 
  199.  * @see ModelMap#addAllAttributes(Map) 
  200.  * @see #getModelMap() 
  201.  */  
  202. public ModelAndView addAllObjects(Map<String, ?> modelMap) {  
  203.     getModelMap().addAllAttributes(modelMap);  
  204.     return this;  
  205. }  
  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 = ;  
  218.     this.model = ;  
  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 ==  && 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. /** 
  243.  * Return diagnostic information about this model and view. 
  244.  */  
  245. @Override  
  246. public String toString() {  
  247.     StringBuilder sb = new StringBuilder("ModelAndView: ");  
  248.     if (isReference()) {  
  249.         sb.append("reference to view with name '").append(this.view).append("'");  
  250.     }  
  251.     else {  
  252.         sb.append("materialized View is [").append(this.view).append(']');  
  253.     }  
  254.     sb.append("; model is ").append(this.model);  
  255.     return sb.toString();  
  256. }  
    在源碼中有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. ...  
  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對象。

[java] view plain copy
  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 != ){  
  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實現,可以根據模型屬性的具體類型自動生成模型屬性的名稱。 

[java] view plain copy
  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 != ){  
  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方法的作用,用來在一個請求過程中傳遞處理的數據。通過以下方法向頁面傳遞參數: 

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); 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章