注意:如果方法声明了注解@ResponseBody ,则会直接将返回值输出到页面。

首先介绍ModelMap[Model]和ModelAndView的作用

Model 是一个接口, 其实现类为ExtendedModelMap,继承了ModelMap类。ModelMap

ModelMap对象主要用于传递控制方法处理数据到结果页面,也就是说我们把结果页面上需要的数据放到ModelMap对象中即可,他的作用类似于request对象的setAttribute方法的作用,用来在一个请求过程中传递处理的数据。通过以下方法向页面传递参数:

addAttribute(String key,Object value);

在页面上可以通过el变量方式$key或者bboss的一系列数据展示标签获取并展示modelmap中的数据。

modelmap本身不能设置页面跳转的url地址别名或者物理跳转地址,那么我们可以通过控制器方法的返回值来设置跳转url地址别名或者物理跳转地址。

ModelAndView

ModelAndView对象有两个作用:

作用一 设置转向地址,如下所示(这也是ModelAndView和ModelMap的主要区别)

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

作用二 用于传递控制方法处理结果数据到结果页面,也就是说我们把需要在结果页面上需要的数据放到ModelAndView对象中即可,他的作用类似于request对象的setAttribute方法的作用,用来在一个请求过程中传递处理的数据。通过以下方法向页面传递参数:

addObject(String key,Object value);

在页面上可以通过el变量方式$key或者bboss的一系列数据展示标签获取并展示ModelAndView中的数据。

作用介绍完了后,接下来介绍使用方法

ModelMap

ModelMap的实例是由bboss mvc框架自动创建并作为控制器方法参数传入,用户无需自己创建。

public String xxxxmethod(String someparam,ModelMap model)

{

//省略方法处理逻辑若干

//将数据放置到ModelMap对象model中,第二个参数可以是任何java类型

model.addAttribute("key",someparam);

......

//返回跳转地址

return "path:handleok";

}

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;//该属性用来存储处理后的结果数据

/**

* 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个构造函数,如何用?是一个重点。构造ModelAndView对象当控制器处理完请求时,通常会将包含视图名称或视图对象以及一些模型属性的ModelAndView对象返回到DispatcherServlet。因此,经常需要在控制器中构造ModelAndView对象。ModelAndView类提供了几个重载的构造器和一些方便的方法,让你可以根据自己的喜好来构造ModelAndView对象。这些构造器和方法以类似的方式支持视图名称和视图对象。通过ModelAndView构造方法可以指定返回的页面名称,也可以通过setViewName()方法跳转到指定的页面 , 使用addObject()设置需要返回的值,addObject()有几个不同参数的方法,可以默认和指定返回对象的名字。

(1)当你只有一个模型属性要返回时,可以在构造器中指定该属性来构造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);  //其中,welcome为跳转的页面,第一个today为key,第二个today为value

}

}

(2)如果有不止一个属性要返回,可以先将它们传递到一个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 model = new HashMap();

if(courtName != null){

model.put("courtName",courtName);

model.put("reservations",reservationService.query(courtName));

}

return new ModelAndView("reservationQuery",model);        //"reservationQuery"为返回页面,model是用来承接姚返回到前端页面的值得集合map

}

}

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)    //返回页面和传递很多前端需要的对象,放进model中

ModelAndView(View view, String  modelName, Object  modelObject )    // 返回页面,只需传递一个参数到前端,对象名为modelName,其对应的值为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);

ModelAndView的实例是由用户手动创建的,这也是和ModelMap的一个区别。

public ModelAndView xxxxmethod(String someparam)

{

//省略方法处理逻辑若干

//构建ModelAndView实例,并设置跳转地址

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

//将数据放置到ModelAndView对象view中,第二个参数可以是任何java类型

view.addObject("key",someparam);

......

//返回ModelAndView对象view

return view;

}

到此bboss mvc中ModelMap和ModelAndView两个对象的作用和使用方法介绍完毕

如下为我自己写的测试代码

//getBusinessIdListByIp方法中同时使用了Model(其实为ModelMap),和ModelAndView ,但是ModelAndView 需要返回,而Model不需要

@RequestMapping(value = "/demo",method = RequestMethod.GET)

public ModelAndView getBusinessIdListByIp(@RequestParam("ip") String ip,@RequestParam("phoneId") String phoneId,Model model){

ModelAndView mav = new ModelAndView();

model.addAttribute("ip", ip);

model.addAttribute("phoneId", phoneId);

mav.addObject(model);

mav.setViewName("user/mav");

return mav;

}

@RequestMapping(value = "/demo2",method = RequestMethod.GET)

public ModelAndView getBusinessIdListByIp(){

return newModelAndView("view/list")

java model类作用_SPRING框架中ModelAndView、Model、ModelMap区别及详细分析相关推荐

  1. java 逻辑或 作用_Java开发中与之间的区别,你真的知道吗?

    &与&& 首先来讲一下&&,这个在java逻辑运算符里面被称为短路与,它与&逻辑与只差了一个& ,但是区别却很大,它的作用是如果前面的表达式运行 ...

  2. openopc.opcerror: dispatch: 无效的类字符串_实战PyQt5: 064-MV框架中的Model类

    模型(Model)简介 在Model-View框架中,模型(Model)为视图(View)和委托(Delegate)使用数据提供了标准接口.大多数情况下模型中并不真正存储数据(如果只有少量的数据,可以 ...

  3. SpringMVC框架中ModelAndView、Model、ModelMap的区别与使用

    1. Model Model 是一个接口, 其实现类为ExtendedModelMap,继承了ModelMap类. public class ExtendedModelMap extends Mode ...

  4. Spring框架中ModelAndView用法分享

    [写在前面]:很久没写博客了,从毕业到web开发快1个月了,接触的比较多的当然是jsp.js和Spring.其中对ModelAndView印象深刻,使用频繁,特辑之. 0.[前言]:使用ModelAn ...

  5. ir指令、立即数的作用_AI框架中图层IR的分析

    AI框架图层IR的分析 前段时间一直忙于HC大会和MindSpore1.0的版本准备,国庆期间终于有点时间来交作业了,本文是AI框架分析专栏的第二篇,总体目录参见: AI框架的演进趋势和MindSpo ...

  6. java风清扬简介_Spring 框架简介

    Spring 是一个开源框架,是为了解决企业应用程序开发复杂性而创建的.框架的主要优势之一就是其分层架构,分层架构允许您选择使用哪一个组件,同时为 J2EE 应用程序开发提供集成的框架. Spring ...

  7. 设计模式_spring框架中常用的8种设计模式

    spring框架中常用到的8种设计模式清单如下: 设计模式 使用地方 备注 工厂模式 BeanFactory ApplicationContext 单例模式 Spring中的Bean 代理模式 Spr ...

  8. java 主类作用_JAVA 关键字及其作用解释

    3. 程序控制语句 1) break 跳出,中断 break 关键字用于提前退出 for.while 或 do 循环,或者在 switch 语句中用来结束 case 块. break 总是退出最深层的 ...

  9. java中将类放入包中,Java 包

    Java 允许使用包(package)将类组织起来.借助于包可以方便地组织自己的代码,并将自己的代码与别人提供的代码库分开管理.使用包的主要原因是确保类名的唯一性.标准的 Java 类库分布在多个包中 ...

最新文章

  1. spring之java配置(springboot推荐的配置方式)
  2. 计算机控制闪光灯,摄影技巧 闪灯篇 光圈控制主体 快门控制场景 闪光灯又该如何调整输出功率?...
  3. 2022年跨境电商新玩法:Tik Tok私域流量沉淀+电商平台流量承接
  4. Windows2000下Api函数的拦截分析
  5. mysql中常用的时间工具
  6. 解析淘宝商城缘何更名“天猫”
  7. Entity Framework Fluent API
  8. 凸优化第二章凸集 2.6 对偶锥与广义不等式
  9. 微信话术自动回复机器人软件
  10. PLSQL调整SQL字体大小
  11. 软件维护类型的基础知识
  12. Mac计算查看文件Md5
  13. 电脑桌面计算机图标下不显示文字,为什么电脑桌面上的图标文下面没有显文字...
  14. Dropping Balls 小球下落
  15. 千岛湖2日团建旅行!游览天下第一秀水,感受湖岛遍布的磅礴气势!_团建拓展_嗨牛团建_杭州站...
  16. 微信提现报证书已过期
  17. APP微信支付的后台实现
  18. JMeter 常用的几种断言方法,你会几种呢?
  19. 实现移动端H5页面调用摄像头
  20. 软文营销常用的方式有哪些?如何写出优秀的软文

热门文章

  1. CUDA 深入浅出谈[转]
  2. 个人作业2---必应词典案例分析
  3. 25年,100亿美元!人类「第二只眼」韦伯望远镜升空,寻找宇宙开天辟地那束光...
  4. 「 每日一练,快乐水题 」728. 自除数
  5. 5.nginx访问控制
  6. Connection to node -1 (/ip:9092) could not be established. Broker may not be available.
  7. 《Java入门从笨鸟到菜鸟》读后感(三)
  8. python中幂运算_python中幂运算
  9. 数据结构与算法之时间复杂度与空间复杂度
  10. HTML视频无法自动播放问题