SpringMVC ModelAndView的用法使用详解的用法使用详解
主要介绍了SpringMVC ModelAndView的用法使用详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参
考学习价值,需要的朋友们下面随着小编来一起学习学习吧
(一)使用ModelAndView类用来存储处理完后的结果数据,以及显示该数据的视图。从名字上看ModelAndView中的Model代表模型,View代表视
图,这个名字就很好地解释了该类的作用。业务处理器调用模型层处理完用户请求后,把结果数据存储在该类的model属性中,把要返回的视图信
息存储在该类的view属性中,然后让该ModelAndView返回该Spring MVC框架。框架通过调用配置文件中定义的视图解析器,对该对象进行解析,
最后把结果数据显示在指定的页面上。
具体作用:
1、返回指定页面、返回指定页面
ModelAndView构造方法可以指定返回的页面名称,
也可以通过setViewName()方法跳转到指定的页面 ,
2、返回所需数值、返回所需数值
使用addObject()设置需要返回的值,addObject()有几个不同参数的方法,可以默认和指定返回对象的名字。
1、【其源码】:熟悉一个类的用法,最好从其源码入手。
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.
评论0
最新资源