(一)使用ModelAndView類用來存儲處理完後的結果數據,以及顯示該數據的視圖。java
從名字上看ModelAndView中的Model表明模型,View表明視圖,這個名字就很好地解釋了該類的做用。業務處理器調用模型層處理完用戶請求後,把結果數據存儲在該類的model屬性中,把要返回的視圖信息存儲在該類的view屬性中,而後讓該ModelAndView返回該Spring MVC框架。框架經過調用配置文件中定義的視圖解析器,對該對象進行解析,最後把結果數據顯示在指定的頁面上。 web
具體做用:spring
一、返回指定頁面mvc
ModelAndView構造方法能夠指定返回的頁面名稱,app
也能夠經過setViewName()方法跳轉到指定的頁面 ,框架
二、返回所需數值jsp
使用addObject()設置須要返回的值,addObject()有幾個不一樣參數的方法,能夠默認和指定返回對象的名字。ide
(二)【源碼】函數
1. 熟悉一個類的用法,最好從其源碼入手。post
public class ModelAndView { /** View instance or view name String */ private Object view //該屬性用來存儲返回的視圖信息 /** Model Map */ private ModelMap model;//<span style="color: rgb(0, 130, 0); font-family: Consolas, 'Courier New', Courier, mono, serif; line-height: 18px;">該屬性用來存儲處理後的結果數據</span> /** * Indicates whether or not this instance has been cleared with a call to {@link #clear()}. */ private boolean cleared = false; /** * Default constructor for bean-style usage: populating bean * properties instead of passing in constructor arguments. * @see #setView(View) * @see #setViewName(String) */ public ModelAndView() { } /** * Convenient constructor when there is no model data to expose. * Can also be used in conjunction with <code>addObject</code>. * @param viewName name of the View to render, to be resolved * by the DispatcherServlet's ViewResolver * @see #addObject */ public ModelAndView(String viewName) { this.view = viewName; } /** * Convenient constructor when there is no model data to expose. * Can also be used in conjunction with <code>addObject</code>. * @param view View object to render * @see #addObject */ public ModelAndView(View view) { this.view = view; } /** * Creates new ModelAndView given a view name and a model. * @param viewName name of the View to render, to be resolved * by the DispatcherServlet's ViewResolver * @param model Map of model names (Strings) to model objects * (Objects). Model entries may not be <code>null</code>, but the * model Map may be <code>null</code> if there is no model data. */ public ModelAndView(String viewName, Map<String, ?> model) { this.view = viewName; if (model != null) { getModelMap().addAllAttributes(model); } } /** * Creates new ModelAndView given a View object and a model. * <emphasis>Note: the supplied model data is copied into the internal * storage of this class. You should not consider to modify the supplied * Map after supplying it to this class</emphasis> * @param view View object to render * @param model Map of model names (Strings) to model objects * (Objects). Model entries may not be <code>null</code>, but the * model Map may be <code>null</code> if there is no model data. */ public ModelAndView(View view, Map<String, ?> model) { this.view = view; if (model != null) { getModelMap().addAllAttributes(model); } } /** * Convenient constructor to take a single model object. * @param viewName name of the View to render, to be resolved * by the DispatcherServlet's ViewResolver * @param modelName name of the single entry in the model * @param modelObject the single model object */ public ModelAndView(String viewName, String modelName, Object modelObject) { this.view = viewName; addObject(modelName, modelObject); } /** * Convenient constructor to take a single model object. * @param view View object to render * @param modelName name of the single entry in the model * @param modelObject the single model object */ public ModelAndView(View view, String modelName, Object modelObject) { this.view = view; addObject(modelName, modelObject); } /** * Set a view name for this ModelAndView, to be resolved by the * DispatcherServlet via a ViewResolver. Will override any * pre-existing view name or View. */ public void setViewName(String viewName) { this.view = viewName; } /** * Return the view name to be resolved by the DispatcherServlet * via a ViewResolver, or <code>null</code> if we are using a View object. */ public String getViewName() { return (this.view instanceof String ? (String) this.view : null); } /** * Set a View object for this ModelAndView. Will override any * pre-existing view name or View. */ public void setView(View view) { this.view = view; } /** * Return the View object, or <code>null</code> if we are using a view name * to be resolved by the DispatcherServlet via a ViewResolver. */ public View getView() { return (this.view instanceof View ? (View) this.view : null); } /** * Indicate whether or not this <code>ModelAndView</code> has a view, either * as a view name or as a direct {@link View} instance. */ public boolean hasView() { return (this.view != null); } /** * Return whether we use a view reference, i.e. <code>true</code> * if the view has been specified via a name to be resolved by the * DispatcherServlet via a ViewResolver. */ public boolean isReference() { return (this.view instanceof String); } /** * Return the model map. May return <code>null</code>. * Called by DispatcherServlet for evaluation of the model. */ protected Map<String, Object> getModelInternal() { return this.model; } /** * Return the underlying <code>ModelMap</code> instance (never <code>null</code>). */ public ModelMap getModelMap() { if (this.model == null) { this.model = new ModelMap(); } return this.model; } /** * Return the model map. Never returns <code>null</code>. * To be called by application code for modifying the model. */ public Map<String, Object> getModel() { return getModelMap(); } /** * Add an attribute to the model. * @param attributeName name of the object to add to the model * @param attributeValue object to add to the model (never <code>null</code>) * @see ModelMap#addAttribute(String, Object) * @see #getModelMap() */ public ModelAndView addObject(String attributeName, Object attributeValue) { getModelMap().addAttribute(attributeName, attributeValue); return this; } /** * Add an attribute to the model using parameter name generation. * @param attributeValue the object to add to the model (never <code>null</code>) * @see ModelMap#addAttribute(Object) * @see #getModelMap() */ public ModelAndView addObject(Object attributeValue) { getModelMap().addAttribute(attributeValue); return this; } /** * Add all attributes contained in the provided Map to the model. * @param modelMap a Map of attributeName -> attributeValue pairs * @see ModelMap#addAllAttributes(Map) * @see #getModelMap() */ public ModelAndView addAllObjects(Map<String, ?> modelMap) { getModelMap().addAllAttributes(modelMap); return this; } /** * Clear the state of this ModelAndView object. * The object will be empty afterwards. * <p>Can be used to suppress rendering of a given ModelAndView object * in the <code>postHandle</code> method of a HandlerInterceptor. * @see #isEmpty() * @see HandlerInterceptor#postHandle */ public void clear() { this.view = null; this.model = null; this.cleared = true; } /** * Return whether this ModelAndView object is empty, * i.e. whether it does not hold any view and does not contain a model. */ public boolean isEmpty() { return (this.view == null && CollectionUtils.isEmpty(this.model)); } /** * Return whether this ModelAndView object is empty as a result of a call to {@link #clear} * i.e. whether it does not hold any view and does not contain a model. * <p>Returns <code>false</code> if any additional state was added to the instance * <strong>after</strong> the call to {@link #clear}. * @see #clear() */ public boolean wasCleared() { return (this.cleared && isEmpty()); } /** * Return diagnostic information about this model and view. */ @Override public String toString() { StringBuilder sb = new StringBuilder("ModelAndView: "); if (isReference()) { sb.append("reference to view with name '").append(this.view).append("'"); } else { sb.append("materialized View is [").append(this.view).append(']'); } sb.append("; model is ").append(this.model); return sb.toString(); }
在源碼中有7個構造函數,如何用?是一個重點。
構造ModelAndView對象當控制器處理完請求時,一般會將包含視圖名稱或視圖對象以及一些模型屬性的ModelAndView對象返回到DispatcherServlet。
所以,常常須要在控制器中構造ModelAndView對象。
ModelAndView類提供了幾個重載的構造器和一些方便的方法,讓你能夠根據本身的喜愛來構造ModelAndView對象。這些構造器和方法以相似的方式支持視圖名稱和視圖對象。
經過ModelAndView構造方法能夠指定返回的頁面名稱,也能夠經過setViewName()方法跳轉到指定的頁面 , 使用addObject()設置須要返回的值,addObject()有幾個不一樣參數的方法,能夠默認和指定返回對象的名字。
2. 當你只有一個模型屬性要返回時,能夠在構造器中指定該屬性來構造ModelAndView對象
package com.apress.springrecipes.court.web; ... import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.AbstractController; public class WelcomeController extends AbstractController{ public ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)throws Exception{ Date today = new Date(); return new ModelAndView("welcome","today",today); } }
3. 若是有不止一個屬性要返回,能夠先將它們傳遞到一個Map中再來構造ModelAndView對象。
package com.apress.springrecipes.court.web; ... import org.springframework.web.servlet.ModelAndView; import org. springframework.web.servlet.mvc.AbstractController; public class ReservationQueryController extends AbstractController{ ... public ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)throws Exception{ ... Map<String,Object> model = new HashMap<String,Object>(); if(courtName != null){ model.put("courtName",courtName); model.put("reservations",reservationService.query(courtName)); } return new ModelAndView("reservationQuery",model); } }
4. Spring也提供了ModelMap,這是java.util.Map實現,能夠根據模型屬性的具體類型自動生成模型屬性的名稱。
package com.apress.springrecipes.court.web; ... import org.springframework.ui.ModelMap; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.AbstractController; public class ReservationQueryController extends AbstractController{ ... public ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)throws Exception{ ... ModelMap model = new ModelMap(); if(courtName != null){ model.addAttribute("courtName",courtName); model.addAttribute("reservations",reservationService.query(courtName)); } return new ModelAndView("reservationQuery",model); } }
這裏,我又想多說一句:ModelMap對象主要用於傳遞控制方法處理數據到結果頁面,
也就是說咱們把結果頁面上須要的數據放到ModelMap對象中便可,他的做用相似於request對象的setAttribute方法的做用,用來在一個請求過程當中傳遞處理的數據。
經過如下方法向頁面傳遞參數:
addAttribute(String key,Object value); //modelMap的方法
在頁面上能夠經過el變量方式${key}或者bboss的一系列數據展現標籤獲取並展現modelmap中的數據。
modelmap自己不能設置頁面跳轉的url地址別名或者物理跳轉地址,那麼咱們能夠經過控制器方法的返回值來設置跳轉url地址別名或者物理跳轉地址。 好比
public String xxxxmethod(String someparam,ModelMap model) { //省略方法處理邏輯若干 //將數據放置到ModelMap對象model中,第二個參數能夠是任何java類型 model.addAttribute("key",someparam); ...... //返回跳轉地址 return "path:handleok"; }
在這些構造函數中最簡單的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)
5. 【方法使用】:給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);
6.【做用簡介】:
ModelAndView對象有兩個做用:
做用一: 設置轉向地址,以下所示(這也是ModelAndView和ModelMap的主要區別)
ModelAndView view = new ModelAndView("path:ok");
做用二 :用於傳遞控制方法處理結果數據到結果頁面,也就是說咱們把須要在結果頁面上須要的數據放到ModelAndView對象中便可,
他的做用相似於request對象的setAttribute方法的做用,用來在一個請求過程當中傳遞處理的數據。經過如下方法向頁面傳遞參數:
addObject(String key,Object value);
7. ModelAndView重定向
spring web framework利用ModelAndView也能實現forward、redirec
public ModelAndView getPage404MV() { ModelAndView mv = new ModelAndView("redirect:/404.htm"); return mv; }
//第三個參數(UserModel user)默認爲綁定對象 @RequestMapping(value = "/user/save", method = RequestMethod.POST) public ModelAndView saveUser(HttpServletRequest request, HttpServletResponse response,UserModel user) throws Exception { ModelAndView mv = new ModelAndView("/user/save/result");//默認爲forward模式 // ModelAndView mv = new ModelAndView("redirect:/user/save/result");//redirect模式 mv.addObject("message","保存用戶成功!"); return mv; }
map返回數據
@RequestMapping("/demo2/show") public Map<String, String> getMap() { Map<String, String> map = new HashMap<String, String>(); map.put("key1", "value-1"); map.put("key2", "value-2"); return map; }
8.SpringMVC:處理器方法返回值——返回ModelAndView以及String
(1) 返回ModelAndView:
應用場景:
若處理器對請求處理事後,不只要進行跳轉,並且在跳轉過程當中還要傳遞數據,此時使用ModelAndView較爲方便。
(2) 返回String:
a、返回物理視圖名稱:
這樣在地址欄裏輸入xxx/some.do就能夠跳轉到welcome.jsp頁面。
b、返回邏輯視圖名稱:
(1)、在spring容器註冊視圖解析器:
(2)、處理器:
這個return的welcome和註冊的視圖解析器能夠拼接出WEB-INF/jsp/welcome.jsp的地址。
c、spring容器裏註冊視圖對象:
(1)、在spring容器裏註冊視圖對象:
(2)、處理器:
注意:視圖解析器,會按照註冊前後順序進行匹配,爲此有必要添加優先級。