struts2 18拦截器详解(十)
ModelDrivenInterceptor
该拦截器处于defaultStack中的第九的位置,在ScopedModelDrivenInterceptor拦截器之后,要使该拦截器有效的话,Action必须实现ModelDriven接口,该接口就一个方法:getModel(),ModelDrivenInterceptor拦截器主要做的事就是调用Action的getModel()方法然后把返回的model压入值栈(如果不为null)。如果Action实现了ScopedModelDriven接口也就实现了ModelDriven接口,因为ScopedModelDrivenInterceptor在执行的过程肯定会返回一个model对象再调用Action的setModel(model)方法,如果Action对model进行了接收,那么在执行到ModelDrivenInterceptor拦截器的时候,Action的getModel()方法返回的就是ScopedModelDrivenInterceptor拦截器设置进去的值,已经不为null了,所以该model自然就会压入值栈。下面是该拦截器intercept方法源码:
protected static class RefreshModelBeforeResult implements PreResultListener { private Object originalModel = null; protected ModelDriven action; public RefreshModelBeforeResult(ModelDriven action, Object model) { this.originalModel = model; this.action = action; } public void beforeResult(ActionInvocation invocation, String resultCode) { ValueStack stack = invocation.getStack();//获取值栈 CompoundRoot root = stack.getRoot();//获取值栈的root对象 boolean needsRefresh = true; Object newModel = action.getModel();//从Action中获取新的model对象 // Check to see if the new model instance is already on the stack for (Object item : root) { if (item.equals(newModel)) {//如果新的model对象与旧的相同则不刷新 needsRefresh = false; } } // Add the new model on the stack if (needsRefresh) {//如果要刷新 // Clear off the old model instance if (originalModel != null) { root.remove(originalModel);//先移除旧model } if (newModel != null) { stack.push(newModel);//将新model对象压入值栈 } } }}