当前位置: 移动技术网 > IT编程>开发语言>Java > ModelAndViewContainer、ModelMap、Model详细介绍【享学Spring MVC】

ModelAndViewContainer、ModelMap、Model详细介绍【享学Spring MVC】

2019年09月02日  | 移动技术网IT编程  | 我要评论

每篇一句

一个开源的技术产品做得好不好,主要是看你能解决多少非功能性问题(因为功能性问题是所有产品都能够想到的)

前言

写这篇文章非我本意,因为我觉得对如题的这个几个类的了解还是比较基础且简单的一块内容,直到有超过两个同学问过我一些问题的时候:通过聊天发现小伙伴都听说过这几个类,但对于他们的使用、功能定位是傻傻分不清楚的(因为名字上都有很多的相似之处)。
那么书写本文就是当作一篇科普类文章记录下来,已经非常熟悉小伙伴就没太大必要往下继续阅读本文内容了,因为这块不算难的(当然我只是建议而已~)。

modelandviewcontainer

我把这个类放在首位,是因为相较而言它的逻辑性稍强一点,并且对于理解处理器returnvalue返回值的处理上有很好的帮助。

modelandviewcontainer:可以把它定义为modelandview上下文的容器,它承担着整个请求过程中的数据传递工作-->保存着modelview。官方doc对它的解释是这句话:

records model and view related decisions made by {@link handlermethodargumentresolver handlermethodargumentresolvers} and
{@link handlermethodreturnvaluehandler handlermethodreturnvaluehandlers} during the course of invocation of a controller method.

翻译成"人话"便是:记录handlermethodargumentresolverhandlermethodreturnvaluehandler在处理controller的handler方法时 使用的模型model和视图view相关信息.。

当然它除了保存modelview外,还额外提供了一些其它功能。下面我们先来熟悉熟悉它的api、源码:

// @since 3.1
public class modelandviewcontainer {
    // =================它所持有的这些属性还是蛮重要的=================
    // redirect时,是否忽略defaultmodel 默认值是false:不忽略
    private boolean ignoredefaultmodelonredirect = false;
    // 此视图可能是个view,也可能只是个逻辑视图string
    @nullable
    private object view;
    // defaultmodel默认的model
    // 注意:modelmap 只是个map而已,但是实现类bindingawaremodelmap它却实现了org.springframework.ui.model接口
    private final modelmap defaultmodel = new bindingawaremodelmap();
    // 重定向时使用的模型(提供set方法设置进来)
    @nullable
    private modelmap redirectmodel;
    // 控制器是否返回重定向指令
    // 如:使用了前缀"redirect:xxx.jsp"这种,这个值就是true。然后最终是个redirectview
    private boolean redirectmodelscenario = false;
    // http状态码
    @nullable
    private httpstatus status;
    
    private final set<string> nobinding = new hashset<>(4);
    private final set<string> bindingdisabled = new hashset<>(4);

    // 很容易想到,它和@sessionattributes标记的元素有关
    private final sessionstatus sessionstatus = new simplesessionstatus();
    // 这个属性老重要了:标记handler是否**已经完成**请求处理
    // 在链式操作中,这个标记很重要
    private boolean requesthandled = false;
    ...

    public void setviewname(@nullable string viewname) {
        this.view = viewname;
    }
    public void setview(@nullable object view) {
        this.view = view;
    }
    // 是否是视图的引用
    public boolean isviewreference() {
        return (this.view instanceof string);
    }

    // 是否使用默认的model
    private boolean usedefaultmodel() {
        return (!this.redirectmodelscenario || (this.redirectmodel == null && !this.ignoredefaultmodelonredirect));
    }
    
    // 注意子方法和下面getdefaultmodel()方法的区别
    public modelmap getmodel() {
        if (usedefaultmodel()) { // 使用默认视图
            return this.defaultmodel;
        } else {
            if (this.redirectmodel == null) { // 若重定向视图为null,就new一个空的返回
                this.redirectmodel = new modelmap();
            }
            return this.redirectmodel;
        }
    }
    // @since 4.1.4
    public modelmap getdefaultmodel() {
        return this.defaultmodel;
    }

    // @since 4.3 可以设置响应码,最终和modelandview一起被view渲染时候使用
    public void setstatus(@nullable httpstatus status) {
        this.status = status;
    }

    // 以编程方式注册一个**不应**发生数据绑定的属性,对于随后声明的@modelattribute也是不能绑定的
    // 虽然方法是set 但内部是add哦  ~~~~
    public void setbindingdisabled(string attributename) {
        this.bindingdisabled.add(attributename);
    }
    public boolean isbindingdisabled(string name) {
        return (this.bindingdisabled.contains(name) || this.nobinding.contains(name));
    }
    // 注册是否应为相应的模型属性进行数据绑定
    public void setbinding(string attributename, boolean enabled) {
        if (!enabled) {
            this.nobinding.add(attributename);
        } else {
            this.nobinding.remove(attributename);
        }
    }

    // 这个方法需要重点说一下:请求是否已在处理程序中完全处理
    // 举个例子:比如@responsebody标注的方法返回值,无需view继续去处理,所以就可以设置此值为true了
    // 说明:这个属性也就是可通过源生的servletresponse、outputstream来达到同样效果的
    public void setrequesthandled(boolean requesthandled) {
        this.requesthandled = requesthandled;
    }
    public boolean isrequesthandled() {
        return this.requesthandled;
    }

    // =========下面是model的相关方法了==========
    // addattribute/addallattributes/mergeattributes/removeattributes/containsattribute
}

直观的阅读过源码后,至少我能够得到如下结论,分享给大家:

  • 它维护了模型model:包括defaultmodleredirectmodel
  • defaultmodel是默认使用的model,redirectmodel是用于传递redirect时的model
  • controller处理器入参写了model或modelmap类型时候,实际传入的是defaultmodel
    - defaultmodel它实际是bindingawaremodel,是个map。而且继承了modelmap又实现了model接口,所以在处理器中使用modelmodelmap时,其实都是使用同一个对象~~~
    - 可参考mapmethodprocessor,它最终调用的都是mavcontainer.getmodel()方法
  • 若处理器入参类型是redirectattributes类型,最终传入的是redirectmodel
    - 至于为何实际传入的是defaultmodel??参考:redirectattributesmethodargumentresolver,使用的是new redirectattributesmodelmap(databinder)
  • 维护视图view(兼容支持逻辑视图名称)
  • 维护是否redirect信息,及根据这个判断handleradapter使用的是defaultmodel或redirectmodel
  • 维护@sessionattributes注解信息状态
  • 维护handler是否处理标记(重要)

下面我主要花笔墨重点介绍一下它的requesthandled这个属性的作用:

requesthandled属性

1、首先看看isrequesthandled()方法的使用:
requestmappinghandleradaptermavcontainer.isrequesthandled()方法的使用,或许你就能悟出点啥了:

这个方法的执行实际是:handlermethod完全调用执行完成后,就执行这个方法去拿modelandview了(传入了request和modelandviewcontainer

requestmappinghandleradapter:
    @nullable
    private modelandview getmodelandview(modelandviewcontainer mavcontainer modelfactory modelfactory, nativewebrequest webrequest) throws exception {
        // 将列为@sessionattributes的模型属性提升到会话
        modelfactory.updatemodel(webrequest, mavcontainer);
        if (mavcontainer.isrequesthandled()) {
            return null;
        }

        modelmap model = mavcontainer.getmodel();
        modelandview mav = new modelandview(mavcontainer.getviewname(), model, mavcontainer.getstatus());
        // 真正的view 可见modelmap/视图名称、状态httpstatus最终都交给了veiw去渲染
        if (!mavcontainer.isviewreference()) {
            mav.setview((view) mavcontainer.getview());
        }
        
        // 这个步骤:是spring mvc对重定向的支持~~~~
        // 重定向之间传值,使用的redirectattributes这种model~~~~
        if (model instanceof redirectattributes) {
            map<string, ?> flashattributes = ((redirectattributes) model).getflashattributes();
            httpservletrequest request = webrequest.getnativerequest(httpservletrequest.class);
            if (request != null) {
                requestcontextutils.getoutputflashmap(request).putall(flashattributes);
            }
        }
    }

可以看到如果modelandviewcontainer已经被处理过,此处直接返回null,也就是不会再继续处理model和view了~

2、setrequesthandled()方法的使用
作为设置方法,调用的地方有好多个,总结如下:

  • asynctaskmethodreturnvaluehandler:处理返回值类型是webasynctask的方法
// 若返回null,就没必要继续处理了
if (returnvalue == null) {
    mavcontainer.setrequesthandled(true);
    return;
}
  • callablemethodreturnvaluehandler/deferredresultmethodreturnvaluehandler/streamingresponsebodyreturnvaluehandler:处理返回值类型是callable/deferredresult/listenablefuture/completionstage/streamingresponsebody的方法(原理同上)
  • httpentitymethodprocessor:返回值类型是httpentity的方法
// 看一看到,这种返回值的都会标注为已处理,这样就不再需要视图(渲染)了
    @override
    public void handlereturnvalue(@nullable object returnvalue, methodparameter returntype, modelandviewcontainer mavcontainer, nativewebrequest webrequest) throws exception {
        mavcontainer.setrequesthandled(true); // 第一句就是这句代码
        if (returnvalue == null) {
            return;
        }
        ... // 交给消息处理器去写        
        outputmessage.flush();
    }
  • 同上的原理的还有httpheadersreturnvaluehandler/requestresponsebodymethodprocessor/responsebodyemitterreturnvaluehandler等等返回值处理器
  • servletinvocablehandlermethod/handlermethod在处理handler方法时,有时也会标注true已处理(比如:get请求notmodified/已设置了httpstatus状态码/isrequesthandled()==true等等case)。除了这些case,method方法执行完成后可都会显示设置false的(因为执行完handlermethod后,还需要交给视图渲染~)
  • servletresponsemethodargumentresolver:这唯一一个是处理入参时候的。若入参类型是servletresponse/outputstream/writer,并且mavcontainer != null,它就设置为true了(因为spring mvc认为既然你自己引入了response,那你就自己做输出吧,因此使用时此处是需要特别注意的细节地方~)
resolveargument()方法:

        if (mavcontainer != null) {
            mavcontainer.setrequesthandled(true); // 相当于说你自己需要`servletresponse`,那返回值就交给你自己处理吧~~~~
        }

本文最重要类:modelandviewcontainer部分就介绍到这。接下来就介绍就很简单了,轻松且愉快


model

org.springframework.ui.model的概念不管是在mvc设计模式上,还是在spring mvc里都是被经常提到的:它用于控制层给前端返回所需的数据(渲染所需的数据)

//  @since 2.5.1 它是一个接口
public interface model {
    ...
    // addattribute/addallattributes/mergeattributes/containsattribute
    ...
    // return the current set of model attributes as a map.
    map<string, object> asmap();
}

它的继承树如下:
在这里插入图片描述
最重要的那必须是extendedmodelmap啊,它留到介绍modelmap的时候再详说,简单看看其余子类。

redirectattributes

从命名就能看出是和重定向有关的,它扩展了model接口:

// @since 3.1
public interface redirectattributes extends model {
    ...
    // 它扩展的三个方法,均和flash属性有关
    redirectattributes addflashattribute(string attributename, @nullable object attributevalue);
    // 这里没指定key,因为key根据conventions#getvariablename()自动生成
    redirectattributes addflashattribute(object attributevalue);
    // return the attributes candidate for flash storage or an empty map.
    map<string, ?> getflashattributes();
}
redirectattributesmodelmap

它实现了redirectattributes接口,同时也继承自modelmap,所以"间接"实现了model接口的所有方法。

public class redirectattributesmodelmap extends modelmap implements redirectattributes {
    @nullable
    private final databinder databinder;
    private final modelmap flashattributes = new modelmap();
    ...
    @override
    public redirectattributesmodelmap addattribute(string attributename, @nullable object attributevalue) {
        super.addattribute(attributename, formatvalue(attributevalue));
        return this;
    }

    // 可见这里的databinder是用于数据转换的
    // 把所有参数都转换为string类型(因为http都是string传参嘛)
    @nullable
    private string formatvalue(@nullable object value) {
        if (value == null) {
            return null;
        }
        return (this.databinder != null ? this.databinder.convertifnecessary(value, string.class) : value.tostring());
    }
    ...

    @override
    public map<string, object> asmap() {
        return this;
    }
    @override
    public redirectattributes addflashattribute(string attributename, @nullable object attributevalue) {
        this.flashattributes.addattribute(attributename, attributevalue);
        return this;
    }
    ...
}

我认为它唯一自己的做的有意义的事:借助databinder把添加进来的属性参数会转为string类型(为何是转换为string类型,你有想过吗???)~

concurrentmodel

它是spring5.0后才有的,是线程安全的model,并没提供什么新鲜东西,略(运用于有线程安全问题的场景)


modelmap

modelmap继承自linkedhashmap,因此它的本质其实就是个map而已。
它的特点是:借助map的能力间接的实现了org.springframework.ui.model的接口方法,这种设计技巧更值得我们参考学习的(曲线救国的意思有木有~)。
在这里插入图片描述
so,这里只需要看看extendedmodelmap即可。它自己继承自modelmap,没有啥特点,全部是调用父类的方法完成的接口方法复写,喵喵他的子类吧~

bindingawaremodelmap

注意:它和普通modelmap的区别是:它能感知数据校验结果(如果放进来的key存在对应的绑定结果,并且你的value不是绑定结果本身。那就移除掉model_key_prefix + key这个key的键值对~)。

public class bindingawaremodelmap extends extendedmodelmap {

    // 注解复写了map的put方法,一下子就拦截了所有的addattr方法。。。
    @override
    public object put(string key, object value) {
        removebindingresultifnecessary(key, value);
        return super.put(key, value);
    }
    @override
    public void putall(map<? extends string, ?> map) {
        map.foreach(this::removebindingresultifnecessary);
        super.putall(map);
    }

    // 本类处理的逻辑:
    private void removebindingresultifnecessary(object key, object value) {
        // key必须是string类型才会给与处理
        if (key instanceof string) {
            string attributename = (string) key;
            if (!attributename.startswith(bindingresult.model_key_prefix)) {
                string bindingresultkey = bindingresult.model_key_prefix + attributename;
                bindingresult bindingresult = (bindingresult) get(bindingresultkey);

                // 如果有校验结果,并且放进来的value值不是绑定结果本身,那就移除掉绑定结果(相当于覆盖掉)
                if (bindingresult != null && bindingresult.gettarget() != value) {
                    remove(bindingresultkey);
                }
            }
        }
    }
}

spring mvc默认使用的就是这个modelmap,但它提供的感知功能大多数情况下我们都用不着。不过反正也不用你管,乖乖用着呗


modelandview

顾名思义,modelandview指模型和视图的集合,既包含模型又包含视图;modelandview一般可以作为controller的返回值,所以它的实例是开发者自己手动创建的,这也是它和上面的主要区别(上面都是容器创建,然后注入给我们使用的~)。

因为这个类是直接面向开发者的,所以建议里面的一些api还是要熟悉点较好:

public class modelandview {
    @nullable
    private object view; // 可以是view,也可以是string
    @nullable
    private modelmap model;

    // 显然,你也可以自己就放置好一个http状态码进去
    @nullable
    private httpstatus status;  
    // 标记这个实例是否被调用过clear()方法~~~
    private boolean cleared = false;

    // 总共这几个属性:它提供的构造函数非常的多  这里我就不一一列出
    public void setviewname(@nullable string viewname) {
        this.view = viewname;
    }
    public void setview(@nullable view view) {
        this.view = view;
    }
    @nullable
    public string getviewname() {
        return (this.view instanceof string ? (string) this.view : null);
    }
    @nullable
    public view getview() {
        return (this.view instanceof view ? (view) this.view : null);
    }
    public boolean hasview() {
        return (this.view != null);
    }
    public boolean isreference() {
        return (this.view instanceof string);
    }

    // protected方法~~~
    @nullable
    protected map<string, object> getmodelinternal() {
        return this.model;
    }
    public modelmap getmodelmap() {
        if (this.model == null) {
            this.model = new modelmap();
        }
        return this.model;
    }

    // 操作modelmap的一些方法如下:
    // addobject/addallobjects

    public void clear() {
        this.view = null;
        this.model = null;
        this.cleared = true;
    }
    // 前提是:this.view == null 
    public boolean isempty() {
        return (this.view == null && collectionutils.isempty(this.model));
    }
    
    // 竟然用的was,歪果仁果然严谨  哈哈
    public boolean wascleared() {
        return (this.cleared && isempty());
    }
}

很多人疑问:为何controller的处理方法不仅仅可以返回modelandview,还可以通过返回map/model/modelmap等来直接向页面传值呢???如果返回值是后三者,又是如何找到view完成渲染的呢?

这个问题我抛出来,本文不给答案。因为都聊到这了,此问题应该不算难的了,建议小伙伴必须自行弄懂缘由(请不要放过有用的知识点)。若实在有不懂之处可以给留言我会帮你解答的~
答案参考提示:可参阅modelmethodprocessormodelmethodprocessor对返回值的处理模块

绝大多数情况下,我都建议返回modelandview,而不是其它那哥三。因为它哥三都没有指定视图名,所以通过dispatcherservlet.applydefaultviewname()生成的视图名一般都不是我们需要的。(除非你的目录、命名等等都特别特别的规范,那顺便倒是可以省不少事~~~


modelfactory

关于modelfactory它的介绍, 里算是已经详细讲解过了,这里再简述两句它的作用。
modelfactory是用来维护model的,具体包含两个功能

  1. 初始化model
  2. 处理器执行后将model中相应的参数更新到sessionattributes中(处理@modelattribute@sessionattributes

    总结

    本以为本文不会很长的,没想到还是写成了超10000字的中篇文章。希望这篇文章能够帮助你对spring mvc对模型、视图这块核心内容的理解,帮你扫除途中的一些障碍,共勉~
    ==若对spring、springboot、mybatis等源码分析感兴趣,可加我wx:fsx641385712,手动邀请你入群一起飞==

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网