SpringMVC中ModelAndView详解

乔欣 SpringMVC 发布时间:2022-12-02 22:25:27 阅读数:18646 1
下文笔者讲述SpringMVC中常见的一个对象ModelAndView,如下所示

ModelAndView简介

在进行SpringMVC的开发中,我们经常看见一个类型ModelAndView,那么他到底起什么作用呢?
下文笔者将一一道来,如下所示
ModelAndView的功能:
   1.将处理完毕的结果存储在Model中
   2.View代表视图信息
   两者都可以放入到这个对象中,就组成ModelAndView
综上所述ModeAndView的功能: 
1.返回指定页面
   ModelAndView构造方法可以指定返回的页面名称,
    
2.返回所需数值
  使用addObject()设置需要返回的值
   addObject()有几个不同参数的方法,可以默认和指定返回对象的名字。

ModelAndView源码

public class ModelAndView {  
    /** View instance or view name String */  
    private Object view  //该属性用来存储返回的视图信息
/** Model Map */  
private ModelMap model; 

/** 
 * 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();  
}
例:

ModelAndView使用示例

package com.java265.web;  
...  
import org.springframework.web.servlet.ModelAndView;  
import org.springframework.web.servlet.mvc.AbstractController;  
public class TestController extends AbstractController{  
    public ModelAndView handleRequestInternal(HttpServletRequest request,  
        HttpServletResponse response)throws Exception{  
        Date today = new Date();  
        return new ModelAndView("欢迎","java265.com----",today);  
    }  
}  

ModelAndView多个返回值

package com.java265.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);  
    }  
}  

addAttribute向页面发送参数信息

addAttribute(String key,Object value); //modelMap的方法
page上可使用el变量方式${key}

数据展示标签获取
并展示modelmap中数据
例:
public String test(String someparam,ModelMap model)  
{  
     //省略方法处理逻辑若干  
      //将数据放置到ModelMap对象model中,第二个参数可以是任何java类型  
      model.addAttribute("key",someparam);  
     ......  
     //返回跳转地址  
      return "path:redirect";  
}  

ModelAndView常用方法说明

ModelAndView:
  ModelAndView(String viewName, Map model)
Map对象中设定好key与value值,之后可以在视图中取出
  如果只返回一个Model对象,可使用以下方法

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)

ModelAndView设置View的方法

setViewName(String viewName) 和 setView(View view)

ModelAndView设置model的方法

addObject(Object modelObject);
addObject(String modelName, Object modelObject);
addAllObjects(Map modelMap);
 
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaFramework/SpringMVC/202212/5006.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者