Struts2源码阅读(三)_FilterDispatcher核心控制器

来源:互联网 发布:为什么没有网络图标 编辑:程序博客网 时间:2024/05/14 12:29

Dispatcher已经在之前讲过,这就好办了。FilterDispatcher是Struts2的核心控制器,首先看一下init()方法。

[java] view plaincopy
  1.  1public void init(FilterConfig filterConfig) throws ServletException {    
  2.  2.     try {    
  3.  3.         this.filterConfig = filterConfig;    
  4.  4.         initLogging();    
  5.  5.      //创建dispatcher,前面都已经讲过啰    
  6.  6.         dispatcher = createDispatcher(filterConfig);    
  7.  7.         dispatcher.init();    
  8.  8.      //注入将FilterDispatcher中的变量通过container注入,如下面的staticResourceLoader    
  9.  9.         dispatcher.getContainer().inject(this);    
  10. 10.         //StaticContentLoader在BeanSelectionProvider中已经被注入了依赖关系:DefaultStaticContentLoader    
  11. 11.      //可以在struts-default.xml中的<bean>可以找到    
  12. 12.         staticResourceLoader.setHostConfig(new FilterHostConfig(filterConfig));    
  13. 13.     } finally {    
  14. 14.         ActionContext.setContext(null);    
  15. 15.     }    
  16. 16. }    

 

[java] view plaincopy
  1.  1//下面来看DefaultStaticContentLoader的setHostConfig    
  2.  2.     public void setHostConfig(HostConfig filterConfig) {    
  3.  3.           //读取初始参数pakages,调用parse(),解析成类似/org/apache/struts2/static,/template的数组       
  4.  4.         String param = filterConfig.getInitParameter("packages");    
  5.  5.            //"org.apache.struts2.static template org.apache.struts2.interceptor.debugging static"    
  6.  6.         String packages = getAdditionalPackages();    
  7.  7.         if (param != null) {    
  8.  8.             packages = param + " " + packages;    
  9.  9.         }    
  10. 10.         this.pathPrefixes = parse(packages);    
  11. 11.         initLogging(filterConfig);    
  12. 12.     }       

 

现在回去doFilter的方法,每当有一个Request,都会调用这些Filters的doFilter方法

[java] view plaincopy
  1.  1public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {    
  2.  2.     
  3.  3.     HttpServletRequest request = (HttpServletRequest) req;    
  4.  4.     HttpServletResponse response = (HttpServletResponse) res;    
  5.  5.     ServletContext servletContext = getServletContext();    
  6.  6.     
  7.  7.     String timerKey = "FilterDispatcher_doFilter: ";    
  8.  8.     try {    
  9.  9.     
  10. 10.         // FIXME: this should be refactored better to not duplicate work with the action invocation    
  11. 11.         //先看看ValueStackFactory所注入的实现类OgnlValueStackFactory    
  12. 12.      //new OgnlValueStack    
  13. 13.         ValueStack stack = dispatcher.getContainer().getInstance(ValueStackFactory.class).createValueStack();    
  14. 14.         ActionContext ctx = new ActionContext(stack.getContext());    
  15. 15.         ActionContext.setContext(ctx);    
  16. 16.     
  17. 17.         UtilTimerStack.push(timerKey);    
  18. 18.     
  19. 19.  //如果是multipart/form-data就用MultiPartRequestWrapper进行包装    
  20. 20//MultiPartRequestWrapper是StrutsRequestWrapper的子类,两者都是HttpServletRequest实现    
  21. 21//此时在MultiPartRequestWrapper中就会把Files给解析出来,用于文件上传    
  22. 22//所有request都会StrutsRequestWrapper进行包装,StrutsRequestWrapper是可以访问ValueStack    
  23. 23//下面是参见Dispatcher的wrapRequest    
  24. 24.    // String content_type = request.getContentType();    
  25. 25.        //if(content_type!= null&&content_type.indexOf("multipart/form-data")!=-1){    
  26. 26.        //MultiPartRequest multi =getContainer().getInstance(MultiPartRequest.class);    
  27. 27.        //request =new MultiPartRequestWrapper(multi,request,getSaveDir(servletContext));    
  28. 28.        //} else {    
  29. 29.        //     request = new StrutsRequestWrapper(request);    
  30. 30.        // }    
  31. 31.         
  32. 32.         request = prepareDispatcherAndWrapRequest(request, response);    
  33. 33.         ActionMapping mapping;    
  34. 34.         try {    
  35. 35.          //根据url取得对应的Action的配置信息    
  36. 36.          //看一下注入的DefaultActionMapper的getMapping()方法.Action的配置信息存储在 ActionMapping对象中    
  37. 37.             mapping = actionMapper.getMapping(request, dispatcher.getConfigurationManager());    
  38. 38.         } catch (Exception ex) {    
  39. 39.             log.error("error getting ActionMapping", ex);    
  40. 40.             dispatcher.sendError(request, response, servletContext, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ex);    
  41. 41.             return;    
  42. 42.         }    
  43. 43.     
  44. 44.      //如果找不到对应的action配置,则直接返回。比如你输入***.jsp等等                                     
  45. 45.      //这儿有个例外,就是如果path是以“/struts”开头,则到初始参数packages配置的包路径去查找对应的静态资源并输出到页面流中,当然.class文件除外。如果再没有则跳转到404      
  46. 46.         if (mapping == null) {    
  47. 47.             // there is no action in this request, should we look for a static resource?    
  48. 48.             String resourcePath = RequestUtils.getServletPath(request);    
  49. 49.     
  50. 50.             if ("".equals(resourcePath) && null != request.getPathInfo()) {    
  51. 51.                 resourcePath = request.getPathInfo();    
  52. 52.             }    
  53. 53.     
  54. 54.             if (staticResourceLoader.canHandle(resourcePath)) {    
  55. 55.             // 在 DefaultStaticContentLoader 中:return serveStatic && (resourcePath.startsWith("/struts") || resourcePath.startsWith("/static"));    
  56. 56.                 staticResourceLoader.findStaticResource(resourcePath, request, response);    
  57. 57.             } else {    
  58. 58.                 // this is a normal request, let it pass through    
  59. 59.                 chain.doFilter(request, response);    
  60. 60.             }    
  61. 61.             // The framework did its job here    
  62. 62.             return;    
  63. 63.         }    
  64. 64.         //正式开始Action的方法    
  65. 65.         dispatcher.serviceAction(request, response, servletContext, mapping);    
  66. 66.     
  67. 67.     } finally {    
  68. 68.         try {    
  69. 69.             ActionContextCleanUp.cleanUp(req);    
  70. 70.         } finally {    
  71. 71.             UtilTimerStack.pop(timerKey);    
  72. 72.         }    
  73. 73.     }    
  74. 74. }       

 

[java] view plaincopy
  1.  1//下面是ActionMapper接口的实现类 DefaultActionMapper的getMapping()方法的源代码:    
  2.  2.     public ActionMapping getMapping(HttpServletRequest request,    
  3.  3.             ConfigurationManager configManager) {    
  4.  4.         ActionMapping mapping = new ActionMapping();    
  5.  5.         String uri = getUri(request);//得到请求路径的URI,如:testAtcion.action或testAction.do    
  6.  6.     
  7.  7.     
  8.  8.         int indexOfSemicolon = uri.indexOf(";");//修正url的带;jsessionid 时找不到而且的bug    
  9.  9.         uri = (indexOfSemicolon > -1) ? uri.substring(0, indexOfSemicolon) : uri;    
  10. 10.     
  11. 11.         uri = dropExtension(uri, mapping);//删除扩展名,默认扩展名为action    
  12. 12.         if (uri == null) {    
  13. 13.             return null;    
  14. 14.         }    
  15. 15.     
  16. 16.         parseNameAndNamespace(uri, mapping, configManager);//匹配Action的name和namespace    
  17. 17.     
  18. 18.         handleSpecialParameters(request, mapping);//去掉重复参数    
  19. 19.     
  20. 20.         //如果Action的name没有解析出来,直接返回    
  21. 21.     if (mapping.getName() == null) {    
  22. 22.       returnnull;    
  23. 23.     }    
  24. 24.      //下面处理形如testAction!method格式的请求路径    
  25. 25.     if (allowDynamicMethodCalls) {    
  26. 26.       // handle "name!method" convention.    
  27. 27.       String name = mapping.getName();    
  28. 28.       int exclamation = name.lastIndexOf("!");//!是Action名称和方法名的分隔符    
  29. 29.       if (exclamation != -1) {    
  30. 30.         mapping.setName(name.substring(0, exclamation));//提取左边为name    
  31. 31.         mapping.setMethod(name.substring(exclamation + 1));//提取右边的method    
  32. 32.       }    
  33. 33.     }    
  34. 34.     
  35. 35.         return mapping;    
  36. 36.     }      

 

从代码中看出,getMapping()方法返回ActionMapping类型的对象,该对象包含三个参数:Action的name、namespace和要调用的方法method。
  如果getMapping()方法返回ActionMapping对象为null,则FilterDispatcher认为用户请求不是Action,自然另当别论,FilterDispatcher会做一件非常有意思的事:如果请求以/struts开头,会自动查找在web.xml文件中配置的 packages初始化参数,就像下面这样(注意粗斜体部分):

[xhtml] view plaincopy
  1. <filter>    
  2. #    <filter-name>struts2</filter-name>    
  3. #    <filter-class>    
  4. #      org.apache.struts2.dispatcher.FilterDispatcher    
  5. #    </filter-class>    
  6. #    <init-param>    
  7. #      <param-name>packages</param-name>    
  8. #      <param-value>com.lizanhong.action</param-value>    
  9. #    </init-param>    
  10. # lt;/filter>  

 

  FilterDispatcher会将com.lizanhong.action包下的文件当作静态资源处理,即直接在页面上显示文件内容,不过会忽略扩展名为class的文件。比如在com.lizanhong.action包下有一个aaa.txt的文本文件,其内容为“中华人民共和国”,访问http://localhost:8081/Struts2Demo/struts/aaa.txt时会输出txt中的内容
   FilterDispatcher.findStaticResource()方法

[java] view plaincopy
  1.  1. protectedvoid findStaticResource(String name, HttpServletRequest request, HttpServletResponse response) throws IOException {    
  2.  2.   if (!name.endsWith(".class")) {//忽略class文件    
  3.  3.     //遍历packages参数    
  4.  4.     for (String pathPrefix : pathPrefixes) {    
  5.  5.       InputStream is = findInputStream(name, pathPrefix);//读取请求文件流    
  6.  6.       if (is != null) {    
  7.  7.         ...    
  8.  8.         // set the content-type header    
  9.  9.         String contentType = getContentType(name);//读取内容类型    
  10. 10.         if (contentType != null) {    
  11. 11.           response.setContentType(contentType);//重新设置内容类型    
  12. 12.         }    
  13. 13.        ...    
  14. 14.         try {    
  15. 15.          //将读取到的文件流以每次复制4096个字节的方式循环输出    
  16. 16.           copy(is, response.getOutputStream());    
  17. 17.         } finally {    
  18. 18.           is.close();    
  19. 19.         }    
  20. 20.         return;    
  21. 21.       }    
  22. 22.     }    
  23. 23.   }    
  24. 24. }    

 

如果用户请求的资源不是以/struts开头——可能是.jsp文件,也可能是.html文件,则通过过滤器链继续往下传送,直到到达请求的资源为止。
如果getMapping()方法返回有效的ActionMapping对象,则被认为正在请求某个Action,将调用 Dispatcher.serviceAction(request, response, servletContext, mapping)方法,该方法是处理Action的关键所在。
下面就来看serviceAction,这又回到全局变量dispatcher中了

[java] view plaincopy
  1.  1//Load Action class for mapping and invoke the appropriate Action method, or go directly to the Result.    
  2.  2public void serviceAction(HttpServletRequest request, HttpServletResponse response, ServletContext context,    
  3.  3.                               ActionMapping mapping) throws ServletException {    
  4.  4.         //createContextMap方法主要把Application、Session、Request的key value值拷贝到Map中    
  5.  5.         Map<String, Object> extraContext = createContextMap(request, response, mapping, context);    
  6.  6.     
  7.  7.         // If there was a previous value stack, then create a new copy and pass it in to be used by the new Action    
  8.  8.         ValueStack stack = (ValueStack) request.getAttribute(ServletActionContext.STRUTS_VALUESTACK_KEY);    
  9.  9.         boolean nullStack = stack == null;    
  10. 10.         if (nullStack) {    
  11. 11.             ActionContext ctx = ActionContext.getContext();    
  12. 12.             if (ctx != null) {    
  13. 13.                 stack = ctx.getValueStack();    
  14. 14.             }    
  15. 15.         }    
  16. 16.         if (stack != null) {    
  17. 17.             extraContext.put(ActionContext.VALUE_STACK, valueStackFactory.createValueStack(stack));    
  18. 18.         }    
  19. 19.     
  20. 20.         String timerKey = "Handling request from Dispatcher";    
  21. 21.         try {    
  22. 22.             UtilTimerStack.push(timerKey);    
  23. 23.             String namespace = mapping.getNamespace();    
  24. 24.             String name = mapping.getName();    
  25. 25.             String method = mapping.getMethod();    
  26. 26.     
  27. 27.             Configuration config = configurationManager.getConfiguration();    
  28. 28.             //创建一个Action的代理对象,ActionProxyFactory是创建ActionProxy的工厂    
  29. 29.             //参考实现类:DefaultActionProxy和DefaultActionProxyFactory    
  30. 30.             ActionProxy proxy = config.getContainer().getInstance(ActionProxyFactory.class).createActionProxy(    
  31. 31.                     namespace, name, method, extraContext, truefalse);    
  32. 32.     
  33. 33.             request.setAttribute(ServletActionContext.STRUTS_VALUESTACK_KEY, proxy.getInvocation().getStack());    
  34. 34.     
  35. 35.             // if the ActionMapping says to go straight to a result, do it!    
  36. 36.             //如果是Result,则直接转向,关于Result,ActionProxy,ActionInvocation下一讲中再分析    
  37. 37.             if (mapping.getResult() != null) {    
  38. 38.                 Result result = mapping.getResult();    
  39. 39.                 result.execute(proxy.getInvocation());    
  40. 40.             } else {    
  41. 41.                 //执行Action    
  42. 42.                 proxy.execute();    
  43. 43.             }    
  44. 44.     
  45. 45.             // If there was a previous value stack then set it back onto the request    
  46. 46.             if (!nullStack) {    
  47. 47.                 request.setAttribute(ServletActionContext.STRUTS_VALUESTACK_KEY, stack);    
  48. 48.             }    
  49. 49.         } catch (ConfigurationException e) {    
  50. 50.             // WW-2874 Only log error if in devMode    
  51. 51.             if(devMode) {    
  52. 52.                 LOG.error("Could not find action or result", e);    
  53. 53.             }    
  54. 54.             else {    
  55. 55.                 LOG.warn("Could not find action or result", e);    
  56. 56.             }    
  57. 57.             sendError(request, response, context, HttpServletResponse.SC_NOT_FOUND, e);    
  58. 58.         } catch (Exception e) {    
  59. 59.             sendError(request, response, context, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e);    
  60. 60.         } finally {    
  61. 61.             UtilTimerStack.pop(timerKey);    
  62. 62.         }    
  63. 63.     }   

下面开始讲一下主菜ActionProxy了.在这之前最好先去了解一下动态Proxy的基本知识.
ActionProxy是Action的一个代理类,也就是说Action的调用是通过ActionProxy实现的,其实就是调用了ActionProxy.execute()方法,而该方法又调用了ActionInvocation.invoke()方法。归根到底,最后调用的是DefaultActionInvocation.invokeAction()方法。
DefaultActionInvocation()->init()->createAction()。
最后通过调用ActionProxy.exute()-->ActionInvocation.invoke()-->Intercepter.intercept()-->ActionInvocation.invokeActionOnly()-->invokeAction()
这里的步骤是先由ActionProxyFactory创建ActionInvocation和ActionProxy.

[java] view plaincopy
  1. 1public ActionProxy createActionProxy(String namespace, String actionName, String methodName, Map<String, Object> extraContext, boolean executeResult, boolean cleanupContext) {    
  2. 2.         
  3. 3.     ActionInvocation inv = new DefaultActionInvocation(extraContext, true);    
  4. 4.     container.inject(inv);    
  5. 5.     return createActionProxy(inv, namespace, actionName, methodName, executeResult, cleanupContext);    
  6. 6. }    

 

先看DefaultActionInvocation的init方法

[java] view plaincopy
  1.  1public void init(ActionProxy proxy) {    
  2.  2.     this.proxy = proxy;    
  3.  3.     Map<String, Object> contextMap = createContextMap();    
  4.  4.     
  5.  5.     // Setting this so that other classes, like object factories, can use the ActionProxy and other    
  6.  6.     // contextual information to operate    
  7.  7.     ActionContext actionContext = ActionContext.getContext();    
  8.  8.     
  9.  9.     if (actionContext != null) {    
  10. 10.         actionContext.setActionInvocation(this);    
  11. 11.     }    
  12. 12.     //创建Action,struts2中每一个Request都会创建一个新的Action    
  13. 13.     createAction(contextMap);    
  14. 14.     
  15. 15.     if (pushAction) {    
  16. 16.         stack.push(action);    
  17. 17.         contextMap.put("action", action);    
  18. 18.     }    
  19. 19.     
  20. 20.     invocationContext = new ActionContext(contextMap);    
  21. 21.     invocationContext.setName(proxy.getActionName());    
  22. 22.     
  23. 23.     // get a new List so we don't get problems with the iterator if someone changes the list    
  24. 24.     List<InterceptorMapping> interceptorList = new ArrayList<InterceptorMapping>(proxy.getConfig().getInterceptors());    
  25. 25.     interceptors = interceptorList.iterator();    
  26. 26. }    
  27. 27.         
  28. 28protected void createAction(Map<String, Object> contextMap) {    
  29. 29.     // load action    
  30. 30.     String timerKey = "actionCreate: " + proxy.getActionName();    
  31. 31.     try {    
  32. 32.         UtilTimerStack.push(timerKey);    
  33. 33.         //默认为SpringObjectFactory:struts.objectFactory=spring.这里非常巧妙,在struts.properties中可以重写这个属性    
  34. 34.         //在前面BeanSelectionProvider中通过配置文件为ObjectFactory设置实现类    
  35. 35.         //这里以Spring为例,这里会调到SpringObjectFactory的buildBean方法,可以通过ApplicationContext的getBean()方法得到Spring的Bean    
  36. 36.         action = objectFactory.buildAction(proxy.getActionName(), proxy.getNamespace(), proxy.getConfig(), contextMap);    
  37. 37.     } catch (InstantiationException e) {    
  38. 38.         throw new XWorkException("Unable to intantiate Action!", e, proxy.getConfig());    
  39. 39.     } catch (IllegalAccessException e) {    
  40. 40.         throw new XWorkException("Illegal access to constructor, is it public?", e, proxy.getConfig());    
  41. 41.     } catch (Exception e) {    
  42. 42.        ...    
  43. 43.     } finally {    
  44. 44.         UtilTimerStack.pop(timerKey);    
  45. 45.     }    
  46. 46.     
  47. 47.     if (actionEventListener != null) {    
  48. 48.         action = actionEventListener.prepare(action, stack);    
  49. 49.     }    
  50. 50. }    
  51. 51//SpringObjectFactory    
  52. 52public Object buildBean(String beanName, Map<String, Object> extraContext, boolean injectInternal) throws Exception {    
  53. 53.     Object o = null;    
  54. 54.     try {    
  55. 55.         //SpringObjectFactory会通过web.xml中的context-param:contextConfigLocation自动注入ClassPathXmlApplicationContext    
  56. 56.         o = appContext.getBean(beanName);    
  57. 57.     } catch (NoSuchBeanDefinitionException e) {    
  58. 58.         Class beanClazz = getClassInstance(beanName);    
  59. 59.         o = buildBean(beanClazz, extraContext);    
  60. 60.     }    
  61. 61.     if (injectInternal) {    
  62. 62.         injectInternalBeans(o);    
  63. 63.     }    
  64. 64.     return o;    
  65. 65. }    

 

[java] view plaincopy
  1.   1//接下来看看DefaultActionInvocation 的invoke方法    
  2.   2public String invoke() throws Exception {    
  3.   3.     String profileKey = "invoke: ";    
  4.   4.     try {    
  5.   5.         UtilTimerStack.push(profileKey);    
  6.   6.        
  7.   7.         if (executed) {    
  8.   8.             throw new IllegalStateException("Action has already executed");    
  9.   9.         }    
  10.  10.         //递归执行interceptor    
  11.  11.         if (interceptors.hasNext()) {    
  12.  12.             //interceptors是InterceptorMapping实际上是像一个像FilterChain一样的Interceptor链    
  13.  13.             //通过调用Invocation.invoke()实现递归牡循环    
  14.  14.             final InterceptorMapping interceptor = (InterceptorMapping) interceptors.next();    
  15.  15.             String interceptorMsg = "interceptor: " + interceptor.getName();    
  16.  16.             UtilTimerStack.push(interceptorMsg);    
  17.  17.             try {      
  18.  18.                  //在每个Interceptor的方法中都会return invocation.invoke()           
  19.  19.                  resultCode = interceptor.getInterceptor().intercept(DefaultActionInvocation.this);    
  20.  20.                 }    
  21.  21.             finally {    
  22.  22.                 UtilTimerStack.pop(interceptorMsg);    
  23.  23.             }    
  24.  24.         } else {      
  25.  25.             //当所有interceptor都执行完,最后执行Action,invokeActionOnly会调用invokeAction()方法    
  26.  26.             resultCode = invokeActionOnly();    
  27.  27.         }    
  28.  28.     
  29.  29.         // this is needed because the result will be executed, then control will return to the Interceptor, which will    
  30.  30.         // return above and flow through again      
  31.  31.         //在Result返回之前调用preResultListeners     
  32.  32.         //通过executed控制,只执行一次     
  33.  33.         if (!executed) {    
  34.  34.             if (preResultListeners != null) {     
  35.  35.                 for (Object preResultListener : preResultListeners) {     
  36.  36.                     PreResultListener listener = (PreResultListener) preResultListener;    
  37.  37.                                                                     
  38.  38.                     String _profileKey = "preResultListener: ";     
  39.  39.                     try {                                           
  40.  40.                         UtilTimerStack.push(_profileKey);                                 
  41.  41.                         listener.beforeResult(this, resultCode);    
  42.  42.                     }                                               
  43.  43.                     finally {                                       
  44.  44.                         UtilTimerStack.pop(_profileKey);            
  45.  45.                     }                                               
  46.  46.                 }                                                   
  47.  47.             }                                                       
  48.  48.                                                                     
  49.  49.             // now execute the result, if we're supposed to         
  50.  50.             //执行Result                                            
  51.  51.             if (proxy.getExecuteResult()) {                         
  52.  52.                 executeResult();                                    
  53.  53.             }                                                       
  54.  54.                                                                     
  55.  55.             executed = true;                                        
  56.  56.         }                                                           
  57.  57.                                                                     
  58.  58.         return resultCode;                                          
  59.  59.     }                                                               
  60.  60.     finally {                                                       
  61.  61.         UtilTimerStack.pop(profileKey);                             
  62.  62.     }                                                               
  63.  63. }     
  64.  64.     
  65.  65//invokeAction    
  66.  66protected String invokeAction(Object action,ActionConfig actionConfig)throws Exception{    
  67.  67.     String methodName = proxy.getMethod();    
  68.  68.     
  69.  69.     String timerKey = "invokeAction: " + proxy.getActionName();    
  70.  70.     try {    
  71.  71.         UtilTimerStack.push(timerKey);    
  72.  72.     
  73.  73.         boolean methodCalled = false;    
  74.  74.         Object methodResult = null;    
  75.  75.         Method method = null;    
  76.  76.         try {    
  77.  77.             //java反射机制得到要执行的方法    
  78.  78.             method = getAction().getClass().getMethod(methodName, new Class[0]);    
  79.  79.         } catch (NoSuchMethodException e) {    
  80.  80.             // hmm -- OK, try doXxx instead    
  81.  81.             //如果没有对应的方法,则使用do+Xxxx来再次获得方法       
  82.  82.             try {    
  83.  83.                 String altMethodName = "do" + methodName.substring(01).toUpperCase() + methodName.substring(1);    
  84.  84.                 method = getAction().getClass().getMethod(altMethodName, new Class[0]);    
  85.  85.             } catch (NoSuchMethodException e1) {    
  86.  86.                 // well, give the unknown handler a shot    
  87.  87.                 if (unknownHandlerManager.hasUnknownHandlers()) {    
  88.  88.                     try {    
  89.  89.                         methodResult = unknownHandlerManager.handleUnknownMethod(action, methodName);    
  90.  90.                         methodCalled = true;    
  91.  91.                     } catch (NoSuchMethodException e2) {    
  92.  92.                         // throw the original one    
  93.  93.                         throw e;    
  94.  94.                     }    
  95.  95.                 } else {    
  96.  96.                     throw e;    
  97.  97.                 }    
  98.  98.             }    
  99.  99.         }    
  100. 100.         //执行Method    
  101. 101.         if (!methodCalled) {    
  102. 102.             methodResult = method.invoke(action, new Object[0]);    
  103. 103.         }    
  104. 104.         //从这里可以看出可以Action的方法可以返回String去匹配Result,也可以直接返回Result类    
  105. 105.         if (methodResult instanceof Result) {    
  106. 106.             this.explicitResult = (Result) methodResult;    
  107. 107.     
  108. 108.             // Wire the result automatically    
  109. 109.             container.inject(explicitResult);    
  110. 110.             return null;    
  111. 111.         } else {    
  112. 112.             return (String) methodResult;    
  113. 113.         }    
  114. 114.     } catch (NoSuchMethodException e) {    
  115. 115.         throw new IllegalArgumentException("The " + methodName + "() is not defined in action " + getAction().getClass() + "");    
  116. 116.     } catch (InvocationTargetException e) {    
  117. 117.         // We try to return the source exception.    
  118. 118.         Throwable t = e.getTargetException();    
  119. 119.     
  120. 120.         if (actionEventListener != null) {    
  121. 121.             String result = actionEventListener.handleException(t, getStack());    
  122. 122.             if (result != null) {    
  123. 123.                 return result;    
  124. 124.             }    
  125. 125.         }    
  126. 126.         if (t instanceof Exception) {    
  127. 127.             throw (Exception) t;    
  128. 128.         } else {    
  129. 129.             throw e;    
  130. 130.         }    
  131. 131.     } finally {    
  132. 132.         UtilTimerStack.pop(timerKey);    
  133. 133.     }    
  134. 134. }    

 

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

[java] view plaincopy
  1.  1private void executeResult() throws Exception {    
  2.  2.     //根据ResultConfig创建Result     
  3.  3.     result = createResult();    
  4.  4.     
  5.  5.     String timerKey = "executeResult: " + getResultCode();    
  6.  6.     try {    
  7.  7.         UtilTimerStack.push(timerKey);    
  8.  8.         if (result != null) {    
  9.  9.         //开始执行Result,    
  10. 10.         //可以参考Result的实现,如用了比较多的ServletDispatcherResult,ServletActionRedirectResult,ServletRedirectResult     
  11. 11.             result.execute(this);    
  12. 12.         } else if (resultCode != null && !Action.NONE.equals(resultCode)) {    
  13. 13.             throw new ConfigurationException("No result defined for action " + getAction().getClass().getName()    
  14. 14.                     + " and result " + getResultCode(), proxy.getConfig());    
  15. 15.         } else {    
  16. 16.             if (LOG.isDebugEnabled()) {    
  17. 17.                 LOG.debug("No result returned for action " + getAction().getClass().getName() + " at " + proxy.getConfig().getLocation());    
  18. 18.             }    
  19. 19.         }    
  20. 20.     } finally {    
  21. 21.         UtilTimerStack.pop(timerKey);    
  22. 22.     }    
  23. 23. }              
  24. 24.     
  25. 25public Result createResult() throws Exception {    
  26. 26.     //如果Action中直接返回的Result类型,在invokeAction()保存在explicitResult    
  27. 27.     if (explicitResult != null) {                               
  28. 28.         Result ret = explicitResult;                            
  29. 29.         explicitResult = null;                                  
  30. 30.                                                                 
  31. 31.         return ret;                                             
  32. 32.     }    
  33. 33.     //返回的是String则从config中得到当前Action的Results列表    
  34. 34.     ActionConfig config = proxy.getConfig();                    
  35. 35.     Map<String, ResultConfig> results = config.getResults();    
  36. 36.                                                                 
  37. 37.     ResultConfig resultConfig = null;                           
  38. 38.                                                                 
  39. 39.     synchronized (config) {                                     
  40. 40.         try {     
  41. 41.             //通过返回的String来匹配resultConfig      
  42. 42.             resultConfig = results.get(resultCode);             
  43. 43.         } catch (NullPointerException e) {                      
  44. 44.             // swallow                                          
  45. 45.         }                                                       
  46. 46.         if (resultConfig == null) {                             
  47. 47.             // If no result is found for the given resultCode, try to get a wildcard '*' match.    
  48. 48.             //如果找不到对应name的ResultConfig,则使用name为*的Result      
  49. 49.             //说明可以用*通配所有的Result                                  
  50. 50.             resultConfig = results.get("*");    
  51. 51.         }                                       
  52. 52.     }                                           
  53. 53.                                                 
  54. 54.     if (resultConfig != null) {                 
  55. 55.         try {    
  56. 56.             //创建Result     
  57. 57.             return objectFactory.buildResult(resultConfig, invocationContext.getContextMap());    
  58. 58.         } catch (Exception e) {    
  59. 59.             LOG.error("There was an exception while instantiating the result of type " + resultConfig.getClassName(), e);    
  60. 60.             throw new XWorkException(e, resultConfig);    
  61. 61.         }     
  62. 62.     } else if (resultCode != null && !Action.NONE.equals(resultCode) && unknownHandlerManager.hasUnknownHandlers()) {    
  63. 63.         return unknownHandlerManager.handleUnknownResult(invocationContext, proxy.getActionName(), proxy.getConfig(), resultCode);    
  64. 64.     }               
  65. 65.     return null;    
  66. 66. }       
  67. 67.     
  68. 68public Result buildResult(ResultConfig resultConfig, Map<String, Object> extraContext) throws Exception {    
  69. 69.     String resultClassName = resultConfig.getClassName();    
  70. 70.     Result result = null;                                    
  71. 71.                                                              
  72. 72.     if (resultClassName != null) {    
  73. 73.         //buildBean中会用反射机制Class.newInstance来创建bean     
  74. 74.         result = (Result) buildBean(resultClassName, extraContext);    
  75. 75.         Map<String, String> params = resultConfig.getParams();         
  76. 76.         if (params != null) {                                          
  77. 77.             for (Map.Entry<String, String> paramEntry : params.entrySet()) {    
  78. 78.                 try {    
  79. 79.                      //reflectionProvider参见OgnlReflectionProvider;    
  80. 80.               //resultConfig.getParams()就是result配置文件里所配置的参数<param></param>     
  81. 81.                      //setProperties方法最终调用的是Ognl类的setValue方法       
  82. 82.               //这句其实就是把param名值设置到根对象result上    
  83. 83.                     reflectionProvider.setProperty(paramEntry.getKey(), paramEntry.getValue(), result, extraContext, true);    
  84. 84.                 } catch (ReflectionException ex) {     
  85. 85.                     if (LOG.isErrorEnabled())          
  86. 86.                         LOG.error("Unable to set parameter [#0] in result of type [#1]", ex,    
  87. 87.                                 paramEntry.getKey(), resultConfig.getClassName());    
  88. 88.                     if (result instanceof ReflectionExceptionHandler) {               
  89. 89.                         ((ReflectionExceptionHandler) result).handle(ex);             
  90. 90.                     }    
  91. 91.                 }        
  92. 92.             }            
  93. 93.         }                
  94. 94.     }                    
  95. 95.                          
  96. 96.     return result;       
  97. 97. }    

0 0
原创粉丝点击