真实的国产乱ⅩXXX66竹夫人,五月香六月婷婷激情综合,亚洲日本VA一区二区三区,亚洲精品一区二区三区麻豆

成都創(chuàng)新互聯(lián)網(wǎng)站制作重慶分公司

SpringMVC中ModelAndView怎么用

小編給大家分享一下SpringMVC中ModelAndView怎么用,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!

創(chuàng)新互聯(lián)總部坐落于成都市區(qū),致力網(wǎng)站建設(shè)服務(wù)有網(wǎng)站制作、網(wǎng)站設(shè)計、網(wǎng)絡(luò)營銷策劃、網(wǎng)頁設(shè)計、網(wǎng)站維護(hù)、公眾號搭建、重慶小程序開發(fā)、軟件開發(fā)等為企業(yè)提供一整套的信息化建設(shè)解決方案。創(chuàng)造真正意義上的網(wǎng)站建設(shè),為互聯(lián)網(wǎng)品牌在互動行銷領(lǐng)域創(chuàng)造價值而不懈努力!

(一)使用ModelAndView類用來存儲處理完后的結(jié)果數(shù)據(jù),以及顯示該數(shù)據(jù)的視圖。從名字上看ModelAndView中的Model代表模型,View代表視圖,這個名字就很好地解釋了該類的作用。業(yè)務(wù)處理器調(diào)用模型層處理完用戶請求后,把結(jié)果數(shù)據(jù)存儲在該類的model屬性中,把要返回的視圖信息存儲在該類的view屬性中,然后讓該ModelAndView返回該Spring MVC框架。框架通過調(diào)用配置文件中定義的視圖解析器,對該對象進(jìn)行解析,最后把結(jié)果數(shù)據(jù)顯示在指定的頁面上。

具體作用:

1、返回指定頁面

ModelAndView構(gòu)造方法可以指定返回的頁面名稱,

也可以通過setViewName()方法跳轉(zhuǎn)到指定的頁面 ,

2、返回所需數(shù)值

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

1、【其源碼】:熟悉一個類的用法,最好從其源碼入手。

public class ModelAndView {    /** View instance or view name String */   private Object view //該屬性用來存儲返回的視圖信息/** Model Map */ private ModelMap model;//該屬性用來存儲處理后的結(jié)果數(shù)據(jù)  /**  * 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 addObject.  * @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 addObject.  * @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 null, but the  * model Map may be null if there is no model data.  */ public ModelAndView(String viewName, Map model) {   this.view = viewName;   if (model != null) {     getModelMap().addAllAttributes(model);   } }  /**  * Creates new ModelAndView given a View object and a model.  * 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  * @param view View object to render  * @param model Map of model names (Strings) to model objects  * (Objects). Model entries may not be null, but the  * model Map may be null if there is no model data.  */ public ModelAndView(View view, Map 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 null 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 null 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 ModelAndView 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. true  * 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 null.  * Called by DispatcherServlet for evaluation of the model.  */ protected Map getModelInternal() {   return this.model; }  /**  * Return the underlying ModelMap instance (never null).  */ public ModelMap getModelMap() {   if (this.model == null) {     this.model = new ModelMap();   }   return this.model; }  /**  * Return the model map. Never returns null.  * To be called by application code for modifying the model.  */ public Map 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 null)  * @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 null)  * @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 modelMap) {   getModelMap().addAllAttributes(modelMap);   return this; }   /**  * Clear the state of this ModelAndView object.  * The object will be empty afterwards.  *

Can be used to suppress rendering of a given ModelAndView object  * in the postHandle 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.  *

Returns false if any additional state was added to the instance  * after 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個構(gòu)造函數(shù),如何用?是一個重點(diǎn)。

構(gòu)造ModelAndView對象當(dāng)控制器處理完請求時,通常會將包含視圖名稱或視圖對象以及一些模型屬性的ModelAndView對象返回到DispatcherServlet。

因此,經(jīng)常需要在控制器中構(gòu)造ModelAndView對象。

ModelAndView類提供了幾個重載的構(gòu)造器和一些方便的方法,讓你可以根據(jù)自己的喜好來構(gòu)造ModelAndView對象。這些構(gòu)造器和方法以類似的方式支持視圖名稱和視圖對象。

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

(1)當(dāng)你只有一個模型屬性要返回時,可以在構(gòu)造器中指定該屬性來構(gòu)造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);   } }

(2)如果有不止一個屬性要返回,可以先將它們傳遞到一個Map中再來構(gòu)造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 model = new HashMap();     if(courtName != null){       model.put("courtName",courtName);       model.put("reservations",reservationService.query(courtName));     }     return new ModelAndView("reservationQuery",model);   } }

Spring也提供了ModelMap,這是java.util.Map實(shí)現(xiàn),可以根據(jù)模型屬性的具體類型自動生成模型屬性的名稱。

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對象主要用于傳遞控制方法處理數(shù)據(jù)到結(jié)果頁面,

也就是說我們把結(jié)果頁面上需要的數(shù)據(jù)放到ModelMap對象中即可,他的作用類似于request對象的setAttribute方法的作用,用來在一個請求過程中傳遞處理的數(shù)據(jù)。

通過以下方法向頁面?zhèn)鬟f參數(shù):

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

在頁面上可以通過el變量方式${key}或者bboss的一系列數(shù)據(jù)展示標(biāo)簽獲取并展示modelmap中的數(shù)據(jù)。

modelmap本身不能設(shè)置頁面跳轉(zhuǎn)的url地址別名或者物理跳轉(zhuǎn)地址,那么我們可以通過控制器方法的返回值來設(shè)置跳轉(zhuǎn)url地址別名或者物理跳轉(zhuǎn)地址。 比如:

public String xxxxmethod(String someparam,ModelMap model) {    //省略方法處理邏輯若干    //將數(shù)據(jù)放置到ModelMap對象model中,第二個參數(shù)可以是任何java類型    model.addAttribute("key",someparam);    ......    //返回跳轉(zhuǎn)地址    return "path:handleok"; }

在這些構(gòu)造函數(shù)中最簡單的ModelAndView是持有View的名稱返回,之后View名稱被view resolver,也就是實(shí)作org.springframework.web.servlet.View接口的實(shí)例解析,

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

如果您要返回Model對象,則可以使用Map來收集這些Model對象,然后設(shè)定給ModelAndView,使用下面這個版本:

ModelAndView:ModelAndView(String viewName, Map model),Map對象中設(shè)定好key與value值,之后可以在視圖中取出如果您只是要返回一個Model對象,則可以使用下面這個 ModelAndView版本:

ModelAndView(String viewName, String modelName, Object modelObject),其中modelName,您可以在視圖中取出Model并顯示

ModelAndView類別提供實(shí)作View接口的對象來作View的參數(shù):

ModelAndView(View view)ModelAndView(View view, Map model)ModelAndView(View view, String modelName, Object modelObject)

2【方法使用】:給ModelAndView實(shí)例設(shè)置view的方法有兩個:setViewName(String viewName) 和 setView(View view)。

前者是使用viewName,后者是使用預(yù)先構(gòu)造好的View對象。其中前者比較常用。事實(shí)上View是一個接口,而不是一個可以構(gòu)造的具體類,我們只能通過其他途徑來獲取View的實(shí)例。對于viewName,它既可以是jsp的名字,也可以是tiles定義的名字,取決于使用的ViewNameResolver如何理解這個view name。如何獲取View的實(shí)例以后再研究。

而對應(yīng)如何給ModelAndView實(shí)例設(shè)置model則比較復(fù)雜。有三個方法可以使用:

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

3【作用簡介】:

ModelAndView對象有兩個作用:

作用一: 設(shè)置轉(zhuǎn)向地址,如下所示(這也是ModelAndView和ModelMap的主要區(qū)別)

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

作用二 :用于傳遞控制方法處理結(jié)果數(shù)據(jù)到結(jié)果頁面,也就是說我們把需要在結(jié)果頁面上需要的數(shù)據(jù)放到ModelAndView對象中即可,

他的作用類似于request對象的setAttribute方法的作用,用來在一個請求過程中傳遞處理的數(shù)據(jù)。通過以下方法向頁面?zhèn)鬟f參數(shù):

addObject(String key,Object value);

以上是“SpringMVC中ModelAndView怎么用”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對大家有所幫助,如果還想學(xué)習(xí)更多知識,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道!


網(wǎng)頁名稱:SpringMVC中ModelAndView怎么用
本文URL:http://weahome.cn/article/ihopch.html

其他資訊

在線咨詢

微信咨詢

電話咨詢

028-86922220(工作日)

18980820575(7×24)

提交需求

返回頂部