接下来看看DefaultActionInvocation 的invoke方法。
 

Java代码 复制代码  收藏代码
  1.  public void init(ActionProxy proxy) {   
  2.      this.proxy = proxy;   
  3.      Map contextMap = createContextMap();   
  4.   
  5.      // Setting this so that other classes, like object factories, can use the ActionProxy and other   
  6.      // contextual information to operate   
  7.      ActionContext actionContext = ActionContext.getContext();   
  8.   
  9.      if(actionContext != null) {   
  10.          actionContext.setActionInvocation(this);   
  11.      }   
  12.      //创建Action,可Struts2里是每次请求都新建一个Action   
  13.      createAction(contextMap);   
  14.   
  15.      if (pushAction) {   
  16.          stack.push(action);   
  17.          contextMap.put("action", action);   
  18.      }   
  19.   
  20.      invocationContext = new ActionContext(contextMap);   
  21.      invocationContext.setName(proxy.getActionName());   
  22.   
  23.      // get a new List so we don't get problems with the iterator if someone changes the list   
  24.      List interceptorList = new ArrayList(proxy.getConfig().getInterceptors());   
  25.      interceptors = interceptorList.iterator();   
  26.  }   
  27.   
  28.  protected void createAction(Map contextMap) {   
  29.      // load action   
  30.      String timerKey = "actionCreate: "+proxy.getActionName();   
  31.      try {   
  32.          UtilTimerStack.push(timerKey);   
  33.          //这儿默认建立Action是StrutsObjectFactory,实际中我使用的时候都是使用Spring创建的Action,这个时候使用的是SpringObjectFactory   
  34.          action = objectFactory.buildAction(proxy.getActionName(), proxy.getNamespace(), proxy.getConfig(), contextMap);   
  35.      }    
  36.      ..   
  37.      } finally {   
  38.          UtilTimerStack.pop(timerKey);   
  39.      }   
  40.   
  41.      if (actionEventListener != null) {   
  42.          action = actionEventListener.prepare(action, stack);   
  43.      }   
  44.  }   
  45.   
  46.  //接下来看看DefaultActionInvocation 的invoke方法。    
  47. public String invoke() throws Exception {   
  48.      String profileKey = "invoke: ";   
  49.      try {   
  50.          UtilTimerStack.push(profileKey);   
  51.             
  52.          if (executed) {   
  53.              throw new IllegalStateException("Action has already executed");   
  54.          }   
  55.              //先执行interceptors   
  56.          if (interceptors.hasNext()) {   
  57.              final InterceptorMapping interceptor = (InterceptorMapping) interceptors.next();   
  58.              UtilTimerStack.profile("interceptor: "+interceptor.getName(),    
  59.                      new UtilTimerStack.ProfilingBlock<String>() {   
  60.                          public String doProfiling() throws Exception {   
  61.                              resultCode = interceptor.getInterceptor().intercept(DefaultActionInvocation.this);   
  62.                              return null;   
  63.                          }   
  64.              });   
  65.          } else {   
  66.                      //interceptor执行完了之后执行action   
  67.              resultCode = invokeActionOnly();   
  68.          }   
  69.   
  70.          // this is needed because the result will be executed, then control will return to the Interceptor, which will   
  71.          // return above and flow through again   
  72.          if (!executed) {   
  73.                      //在Result返回之前调用preResultListeners   
  74.              if (preResultListeners != null) {   
  75.                  for (Iterator iterator = preResultListeners.iterator();   
  76.                      iterator.hasNext();) {   
  77.                      PreResultListener listener = (PreResultListener) iterator.next();   
  78.                         
  79.                      String _profileKey="preResultListener: ";   
  80.                      try {   
  81.                          UtilTimerStack.push(_profileKey);   
  82.                          listener.beforeResult(this, resultCode);   
  83.                      }   
  84.                      finally {   
  85.                          UtilTimerStack.pop(_profileKey);   
  86.                      }   
  87.                  }   
  88.              }   
  89.   
  90.              // now execute the result, if we're supposed to   
  91.              if (proxy.getExecuteResult()) {   
  92.                  executeResult();   
  93.              }   
  94.   
  95.              executed = true;   
  96.          }   
  97.   
  98.          return resultCode;   
  99.      }   
  100.      finally {   
  101.          UtilTimerStack.pop(profileKey);   
  102.      }   
  103.  }  

    public void init(ActionProxy proxy) {
        this.proxy = proxy;
        Map contextMap = createContextMap();

        // Setting this so that other classes, like object factories, can use the ActionProxy and other
        // contextual information to operate
        ActionContext actionContext = ActionContext.getContext();

        if(actionContext != null) {
            actionContext.setActionInvocation(this);
        }
        //创建Action,可Struts2里是每次请求都新建一个Action
        createAction(contextMap);

        if (pushAction) {
            stack.push(action);
            contextMap.put("action", action);
        }

        invocationContext = new ActionContext(contextMap);
        invocationContext.setName(proxy.getActionName());

        // get a new List so we don't get problems with the iterator if someone changes the list
        List interceptorList = new ArrayList(proxy.getConfig().getInterceptors());
        interceptors = interceptorList.iterator();
    }

    protected void createAction(Map contextMap) {
        // load action
        String timerKey = "actionCreate: "+proxy.getActionName();
        try {
            UtilTimerStack.push(timerKey);
            //这儿默认建立Action是StrutsObjectFactory,实际中我使用的时候都是使用Spring创建的Action,这个时候使用的是SpringObjectFactory
            action = objectFactory.buildAction(proxy.getActionName(), proxy.getNamespace(), proxy.getConfig(), contextMap);
        } 
        ..
        } finally {
            UtilTimerStack.pop(timerKey);
        }

        if (actionEventListener != null) {
            action = actionEventListener.prepare(action, stack);
        }
    }

    //接下来看看DefaultActionInvocation 的invoke方法。 
   public String invoke() throws Exception {
        String profileKey = "invoke: ";
        try {
            UtilTimerStack.push(profileKey);
            
            if (executed) {
                throw new IllegalStateException("Action has already executed");
            }
                //先执行interceptors
            if (interceptors.hasNext()) {
                final InterceptorMapping interceptor = (InterceptorMapping) interceptors.next();
                UtilTimerStack.profile("interceptor: "+interceptor.getName(), 
                        new UtilTimerStack.ProfilingBlock<String>() {
                            public String doProfiling() throws Exception {
                                resultCode = interceptor.getInterceptor().intercept(DefaultActionInvocation.this);
                                return null;
                            }
                });
            } else {
                        //interceptor执行完了之后执行action
                resultCode = invokeActionOnly();
            }

            // this is needed because the result will be executed, then control will return to the Interceptor, which will
            // return above and flow through again
            if (!executed) {
                        //在Result返回之前调用preResultListeners
                if (preResultListeners != null) {
                    for (Iterator iterator = preResultListeners.iterator();
                        iterator.hasNext();) {
                        PreResultListener listener = (PreResultListener) iterator.next();
                        
                        String _profileKey="preResultListener: ";
                        try {
                            UtilTimerStack.push(_profileKey);
                            listener.beforeResult(this, resultCode);
                        }
                        finally {
                            UtilTimerStack.pop(_profileKey);
                        }
                    }
                }

                // now execute the result, if we're supposed to
                if (proxy.getExecuteResult()) {
                    executeResult();
                }

                executed = true;
            }

            return resultCode;
        }
        finally {
            UtilTimerStack.pop(profileKey);
        }
    }

看程序中的if(interceptors.hasNext())语句,当然,interceptors里存储的是interceptorMapping列表(它包括一个Interceptor和一个name),所有的截拦器必须实现Interceptor的intercept方法,而该方法的参数恰恰又是ActionInvocation,在intercept方法中还是调用invocation.invoke(),从而实现了一个Interceptor链的调用。当所有的Interceptor执行完,最后调用invokeActionOnly方法来执行Action相应的方法。
 

Java代码 复制代码  收藏代码
  1. protected String invokeAction(Object action, ActionConfig actionConfig) throws Exception {   
  2.     String methodName = proxy.getMethod();   
  3.     String timerKey = "invokeAction: "+proxy.getActionName();   
  4.     try {   
  5.         UtilTimerStack.push(timerKey);   
  6.            
  7.         boolean methodCalled = false;   
  8.         Object methodResult = null;   
  9.         Method method = null;   
  10.         try {   
  11.             //获得需要执行的方法   
  12.             method = getAction().getClass().getMethod(methodName, new Class[0]);   
  13.         } catch (NoSuchMethodException e) {   
  14.             //如果没有对应的方法,则使用do+Xxxx来再次获得方法   
  15.             try {   
  16.                 String altMethodName = "do" + methodName.substring(01).toUpperCase() + methodName.substring(1);   
  17.                 method = getAction().getClass().getMethod(altMethodName, new Class[0]);   
  18.             } catch (NoSuchMethodException e1) {   
  19.                 // well, give the unknown handler a shot   
  20.                 if (unknownHandler != null) {   
  21.                     try {   
  22.                         methodResult = unknownHandler.handleUnknownActionMethod(action, methodName);   
  23.                         methodCalled = true;   
  24.                     } catch (NoSuchMethodException e2) {   
  25.                         // throw the original one   
  26.                         throw e;   
  27.                     }   
  28.                 } else {   
  29.                     throw e;   
  30.                 }   
  31.             }   
  32.         }   
  33.            
  34.         if (!methodCalled) {   
  35.             methodResult = method.invoke(action, new Object[0]);   
  36.         }   
  37.         //根据不同的Result类型返回不同值   
  38.         //如输出流Result   
  39.         if (methodResult instanceof Result) {   
  40.             this.explicitResult = (Result) methodResult;   
  41.             return null;   
  42.         } else {   
  43.             return (String) methodResult;   
  44.         }   
  45.     } catch (NoSuchMethodException e) {   
  46.         throw new IllegalArgumentException("The " + methodName + "() is not defined in action " + getAction().getClass() + "");   
  47.     } catch (InvocationTargetException e) {   
  48.         // We try to return the source exception.   
  49.         Throwable t = e.getTargetException();   
  50.   
  51.         if (actionEventListener != null) {   
  52.             String result = actionEventListener.handleException(t, getStack());   
  53.             if (result != null) {   
  54.                 return result;   
  55.             }   
  56.         }   
  57.         if (t instanceof Exception) {   
  58.             throw(Exception) t;   
  59.         } else {   
  60.             throw e;   
  61.         }   
  62.     } finally {   
  63.         UtilTimerStack.pop(timerKey);   
  64.     }   
  65. }  

    protected String invokeAction(Object action, ActionConfig actionConfig) throws Exception {
        String methodName = proxy.getMethod();
        String timerKey = "invokeAction: "+proxy.getActionName();
        try {
            UtilTimerStack.push(timerKey);
            
            boolean methodCalled = false;
            Object methodResult = null;
            Method method = null;
            try {
                //获得需要执行的方法
                method = getAction().getClass().getMethod(methodName, new Class[0]);
            } catch (NoSuchMethodException e) {
                //如果没有对应的方法,则使用do+Xxxx来再次获得方法
                try {
                    String altMethodName = "do" + methodName.substring(0, 1).toUpperCase() + methodName.substring(1);
                    method = getAction().getClass().getMethod(altMethodName, new Class[0]);
                } catch (NoSuchMethodException e1) {
                    // well, give the unknown handler a shot
                    if (unknownHandler != null) {
                        try {
                            methodResult = unknownHandler.handleUnknownActionMethod(action, methodName);
                            methodCalled = true;
                        } catch (NoSuchMethodException e2) {
                            // throw the original one
                            throw e;
                        }
                    } else {
                        throw e;
                    }
                }
            }
            
            if (!methodCalled) {
                methodResult = method.invoke(action, new Object[0]);
            }
            //根据不同的Result类型返回不同值
            //如输出流Result
            if (methodResult instanceof Result) {
                this.explicitResult = (Result) methodResult;
                return null;
            } else {
                return (String) methodResult;
            }
        } catch (NoSuchMethodException e) {
            throw new IllegalArgumentException("The " + methodName + "() is not defined in action " + getAction().getClass() + "");
        } catch (InvocationTargetException e) {
            // We try to return the source exception.
            Throwable t = e.getTargetException();

            if (actionEventListener != null) {
                String result = actionEventListener.handleException(t, getStack());
                if (result != null) {
                    return result;
                }
            }
            if (t instanceof Exception) {
                throw(Exception) t;
            } else {
                throw e;
            }
        } finally {
            UtilTimerStack.pop(timerKey);
        }
    }


    好了,action执行完了,还要根据ResultConfig返回到view,也就是在invoke方法中调用executeResult方法。
 

Java代码 复制代码  收藏代码
  1. private void executeResult() throws Exception {   
  2.      //根据ResultConfig创建Result   
  3.      result = createResult();   
  4.      String timerKey = "executeResult: "+getResultCode();   
  5.      try {   
  6.          UtilTimerStack.push(timerKey);   
  7.          if (result != null) {   
  8.              //这儿正式执行:)   
  9.              //可以参考Result的实现,如用了比较多的ServletDispatcherResult,ServletActionRedirectResult,ServletRedirectResult   
  10.              result.execute(this);   
  11.          } else if (resultCode != null && !Action.NONE.equals(resultCode)) {   
  12.              throw new ConfigurationException("No result defined for action " + getAction().getClass().getName()    
  13.                      + " and result " + getResultCode(), proxy.getConfig());   
  14.          } else {   
  15.              if (LOG.isDebugEnabled()) {   
  16.                  LOG.debug("No result returned for action "+getAction().getClass().getName()+" at "+proxy.getConfig().getLocation());   
  17.              }   
  18.          }   
  19.      } finally {   
  20.          UtilTimerStack.pop(timerKey);   
  21.      }   
  22.  }   
  23.  public Result createResult() throws Exception {   
  24.      if (explicitResult != null) {   
  25.          Result ret = explicitResult;   
  26.          explicitResult = null;;   
  27.          return ret;   
  28.      }   
  29.      ActionConfig config = proxy.getConfig();   
  30.      Map results = config.getResults();   
  31.      ResultConfig resultConfig = null;   
  32.      synchronized (config) {   
  33.          try {   
  34.              //根据result名称获得ResultConfig,resultCode就是result的name   
  35.              resultConfig = (ResultConfig) results.get(resultCode);   
  36.          } catch (NullPointerException e) {   
  37.          }   
  38.          if (resultConfig == null) {   
  39.              //如果找不到对应name的ResultConfig,则使用name为*的Result   
  40.              resultConfig = (ResultConfig) results.get("*");   
  41.          }   
  42.      }   
  43.      if (resultConfig != null) {   
  44.          try {   
  45.              //参照StrutsObjectFactory的代码   
  46.              Result result = objectFactory.buildResult(resultConfig, invocationContext.getContextMap());   
  47.              return result;   
  48.          } catch (Exception e) {   
  49.              LOG.error("There was an exception while instantiating the result of type " + resultConfig.getClassName(), e);   
  50.              throw new XWorkException(e, resultConfig);   
  51.          }   
  52.      } else if (resultCode != null && !Action.NONE.equals(resultCode) && unknownHandler != null) {   
  53.          return unknownHandler.handleUnknownResult(invocationContext, proxy.getActionName(), proxy.getConfig(), resultCode);   
  54.      }   
  55.      return null;   
  56.  }   
  57.  //StrutsObjectFactory   
  58.  public Result buildResult(ResultConfig resultConfig, Map extraContext) throws Exception {   
  59.      String resultClassName = resultConfig.getClassName();   
  60.      if (resultClassName == null)   
  61.          return null;   
  62.      //创建Result,因为Result是有状态的,所以每次请求都新建一个   
  63.      Object result = buildBean(resultClassName, extraContext);   
  64.      //这句很重要,后面将会谈到,reflectionProvider参见OgnlReflectionProvider;   
  65.      //resultConfig.getParams()就是result配置文件里所配置的参数<param></param>   
  66.      //setProperties方法最终调用的是Ognl类的setValue方法   
  67.      //这句其实就是把param名值设置到根对象result上   
  68.      reflectionProvider.setProperties(resultConfig.getParams(), result, extraContext);   
  69.      if (result instanceof Result)   
  70.          return (Result) result;   
  71.      throw new ConfigurationException(result.getClass().getName() + " does not implement Result.");   
  72.  }  

   private void executeResult() throws Exception {
        //根据ResultConfig创建Result
        result = createResult();
        String timerKey = "executeResult: "+getResultCode();
        try {
            UtilTimerStack.push(timerKey);
            if (result != null) {
                //这儿正式执行:)
                //可以参考Result的实现,如用了比较多的ServletDispatcherResult,ServletActionRedirectResult,ServletRedirectResult
                result.execute(this);
            } else if (resultCode != null && !Action.NONE.equals(resultCode)) {
                throw new ConfigurationException("No result defined for action " + getAction().getClass().getName() 
                        + " and result " + getResultCode(), proxy.getConfig());
            } else {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("No result returned for action "+getAction().getClass().getName()+" at "+proxy.getConfig().getLocation());
                }
            }
        } finally {
            UtilTimerStack.pop(timerKey);
        }
    }
    public Result createResult() throws Exception {
        if (explicitResult != null) {
            Result ret = explicitResult;
            explicitResult = null;;
            return ret;
        }
        ActionConfig config = proxy.getConfig();
        Map results = config.getResults();
        ResultConfig resultConfig = null;
        synchronized (config) {
            try {
                //根据result名称获得ResultConfig,resultCode就是result的name
                resultConfig = (ResultConfig) results.get(resultCode);
            } catch (NullPointerException e) {
            }
            if (resultConfig == null) {
                //如果找不到对应name的ResultConfig,则使用name为*的Result
                resultConfig = (ResultConfig) results.get("*");
            }
        }
        if (resultConfig != null) {
            try {
                //参照StrutsObjectFactory的代码
                Result result = objectFactory.buildResult(resultConfig, invocationContext.getContextMap());
                return result;
            } catch (Exception e) {
                LOG.error("There was an exception while instantiating the result of type " + resultConfig.getClassName(), e);
                throw new XWorkException(e, resultConfig);
            }
        } else if (resultCode != null && !Action.NONE.equals(resultCode) && unknownHandler != null) {
            return unknownHandler.handleUnknownResult(invocationContext, proxy.getActionName(), proxy.getConfig(), resultCode);
        }
        return null;
    }
    //StrutsObjectFactory
    public Result buildResult(ResultConfig resultConfig, Map extraContext) throws Exception {
        String resultClassName = resultConfig.getClassName();
        if (resultClassName == null)
            return null;
        //创建Result,因为Result是有状态的,所以每次请求都新建一个
        Object result = buildBean(resultClassName, extraContext);
        //这句很重要,后面将会谈到,reflectionProvider参见OgnlReflectionProvider;
        //resultConfig.getParams()就是result配置文件里所配置的参数<param></param>
        //setProperties方法最终调用的是Ognl类的setValue方法
        //这句其实就是把param名值设置到根对象result上
        reflectionProvider.setProperties(resultConfig.getParams(), result, extraContext);
        if (result instanceof Result)
            return (Result) result;
        throw new ConfigurationException(result.getClass().getName() + " does not implement Result.");
    }


   这样,一个Struts2的请求流程基本上就结束了。