Struts2源码阅读(六)_ActionProxyActionInvocation

下面开始讲一下主菜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.

public ActionProxy createActionProxy(String namespace, String actionName, String methodName, Map<String, Object> extraContext, boolean executeResult, boolean cleanupContext) {     ActionInvocation inv = new DefaultActionInvocation(extraContext, true);     container.inject(inv);     return createActionProxy(inv, namespace, actionName, methodName, executeResult, cleanupContext);     
} 

下面先看DefaultActionInvocation的init方法

public void init(ActionProxy proxy) {     this.proxy = proxy;     Map<String, Object> 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中每一个Request都会创建一个新的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<InterceptorMapping> interceptorList = new ArrayList<InterceptorMapping>(proxy.getConfig().getInterceptors());     interceptors = interceptorList.iterator();     
}     protected void createAction(Map<String, Object> contextMap) {     // load action     String timerKey = "actionCreate: " + proxy.getActionName();     try {     UtilTimerStack.push(timerKey);     //默认为SpringObjectFactory:struts.objectFactory=spring.这里非常巧妙,在struts.properties中可以重写这个属性     //在前面BeanSelectionProvider中通过配置文件为ObjectFactory设置实现类     //这里以Spring为例,这里会调到SpringObjectFactory的buildBean方法,可以通过ApplicationContext的getBean()方法得到Spring的Bean     action = objectFactory.buildAction(proxy.getActionName(), proxy.getNamespace(), proxy.getConfig(), contextMap);     } catch (InstantiationException e) {     throw new XWorkException("Unable to intantiate Action!", e, proxy.getConfig());     } catch (IllegalAccessException e) {     throw new XWorkException("Illegal access to constructor, is it public?", e, proxy.getConfig());     } catch (Exception e) {     ...     } finally {     UtilTimerStack.pop(timerKey);     }     if (actionEventListener != null) {     action = actionEventListener.prepare(action, stack);     }     
}     
//SpringObjectFactory     
public Object buildBean(String beanName, Map<String, Object> extraContext, boolean injectInternal) throws Exception {     Object o = null;     try {     //SpringObjectFactory会通过web.xml中的context-param:contextConfigLocation自动注入ClassPathXmlApplicationContext     o = appContext.getBean(beanName);     } catch (NoSuchBeanDefinitionException e) {     Class beanClazz = getClassInstance(beanName);     o = buildBean(beanClazz, extraContext);     }     if (injectInternal) {     injectInternalBeans(o);     }     return o;     
}    


//接下来看看DefaultActionInvocation 的invoke方法     
public String invoke() throws Exception {     String profileKey = "invoke: ";     try {     UtilTimerStack.push(profileKey);     if (executed) {     throw new IllegalStateException("Action has already executed");     }     //递归执行interceptor     if (interceptors.hasNext()) {     //interceptors是InterceptorMapping实际上是像一个像FilterChain一样的Interceptor链     //通过调用Invocation.invoke()实现递归牡循环     final InterceptorMapping interceptor = (InterceptorMapping) interceptors.next();     String interceptorMsg = "interceptor: " + interceptor.getName();     UtilTimerStack.push(interceptorMsg);     try {       //在每个Interceptor的方法中都会return invocation.invoke()            resultCode = interceptor.getInterceptor().intercept(DefaultActionInvocation.this);     }     finally {     UtilTimerStack.pop(interceptorMsg);     }     } else {       //当所有interceptor都执行完,最后执行Action,invokeActionOnly会调用invokeAction()方法     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       //在Result返回之前调用preResultListeners      //通过executed控制,只执行一次      if (!executed) {     if (preResultListeners != null) {      for (Object preResultListener : preResultListeners) {      PreResultListener listener = (PreResultListener) preResultListener;     String _profileKey = "preResultListener: ";      try {                                            UtilTimerStack.push(_profileKey);                                  listener.beforeResult(this, resultCode);     }                                                finally {                                        UtilTimerStack.pop(_profileKey);             }                                                }                                                    }                                                        // now execute the result, if we're supposed to          //执行Result                                             if (proxy.getExecuteResult()) {                          executeResult();                                     }                                                        executed = true;                                         }                                                            return resultCode;                                           }                                                                finally {                                                        UtilTimerStack.pop(profileKey);                              }                                                                
}      //invokeAction     
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 {     //java反射机制得到要执行的方法     method = getAction().getClass().getMethod(methodName, new Class[0]);     } catch (NoSuchMethodException e) {     // hmm -- OK, try doXxx instead     //如果没有对应的方法,则使用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 (unknownHandlerManager.hasUnknownHandlers()) {     try {     methodResult = unknownHandlerManager.handleUnknownMethod(action, methodName);     methodCalled = true;     } catch (NoSuchMethodException e2) {     // throw the original one     throw e;     }     } else {     throw e;     }     }     }     //执行Method     if (!methodCalled) {     methodResult = method.invoke(action, new Object[0]);     }     //从这里可以看出可以Action的方法可以返回String去匹配Result,也可以直接返回Result类     if (methodResult instanceof Result) {     this.explicitResult = (Result) methodResult;     // Wire the result automatically     container.inject(explicitResult);     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方法。

private void executeResult() throws Exception {     //根据ResultConfig创建Result      result = createResult();     String timerKey = "executeResult: " + getResultCode();     try {     UtilTimerStack.push(timerKey);     if (result != null) {     //开始执行Result,     //可以参考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 {     //如果Action中直接返回的Result类型,在invokeAction()保存在explicitResult     if (explicitResult != null) {                                Result ret = explicitResult;                             explicitResult = null;                                   return ret;                                              }     //返回的是String则从config中得到当前Action的Results列表     ActionConfig config = proxy.getConfig();                     Map<String, ResultConfig> results = config.getResults();     ResultConfig resultConfig = null;                            synchronized (config) {                                      try {      //通过返回的String来匹配resultConfig       resultConfig = results.get(resultCode);              } catch (NullPointerException e) {                       // swallow                                           }                                                        if (resultConfig == null) {                              // If no result is found for the given resultCode, try to get a wildcard '*' match.     //如果找不到对应name的ResultConfig,则使用name为*的Result       //说明可以用*通配所有的Result                                   resultConfig = results.get("*");     }                                        }                                            if (resultConfig != null) {                  try {     //创建Result      return objectFactory.buildResult(resultConfig, invocationContext.getContextMap());     } 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) && unknownHandlerManager.hasUnknownHandlers()) {     return unknownHandlerManager.handleUnknownResult(invocationContext, proxy.getActionName(), proxy.getConfig(), resultCode);     }                return null;     
}        public Result buildResult(ResultConfig resultConfig, Map<String, Object> extraContext) throws Exception {     String resultClassName = resultConfig.getClassName();     Result result = null;                                     if (resultClassName != null) {     //buildBean中会用反射机制Class.newInstance来创建bean      result = (Result) buildBean(resultClassName, extraContext);     Map<String, String> params = resultConfig.getParams();          if (params != null) {                                           for (Map.Entry<String, String> paramEntry : params.entrySet()) {     try {     //reflectionProvider参见OgnlReflectionProvider;     //resultConfig.getParams()就是result配置文件里所配置的参数<param></param>      //setProperties方法最终调用的是Ognl类的setValue方法        //这句其实就是把param名值设置到根对象result上     reflectionProvider.setProperty(paramEntry.getKey(), paramEntry.getValue(), result, extraContext, true);     } catch (ReflectionException ex) {      if (LOG.isErrorEnabled())           LOG.error("Unable to set parameter [#0] in result of type [#1]", ex,     paramEntry.getKey(), resultConfig.getClassName());     if (result instanceof ReflectionExceptionHandler) {                ((ReflectionExceptionHandler) result).handle(ex);              }     }         }             }                 }                     return result;        
}   
最后看一张在网上看到的一个调用流程图作为参考:



本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/497912.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

py语言和php,php和python什么区别

python语言的风格Python在设计上坚持了清晰划一的风格&#xff0c;这使得Python成为一门易读、易维护&#xff0c;并且被大量用户所欢迎的、用途广泛的语言。设计者开发时总的指导思想是&#xff0c;对于一个特定的问题&#xff0c;只要有一种最好的方法来解决就好了。这在由Ti…

计算机产业深度报告:云计算与人工智能开启新一轮技术变革周期

来源&#xff1a;乐晴智库概要&#xff1a;每一次的技术迭代都将行业推向新的高度&#xff0c;同时也对产业生态和企业兴衰产生重大影响。纵观整个IT产业的发展史&#xff0c;从1960年代到现在的2010年代&#xff0c;科技行业历经了大型机时代、小型机时代、PC时代、互联网时代…

自动分页,返回时跳回指定页

实现原理&#xff1a; displaytag 自动分页时&#xff0c;只需要提供一个“集合”(name 属性) 和翻页对应的 requestURI 属性&#xff08;也是返回整体的集合&#xff09; 执行翻页时 displaytag 会自动计算出页数&#xff0c;形如&#xff1a; http://localhost:8080/bpp/ma…

java 界面艺术字,Java 在Word文档中添加艺术字

与普通文字相比&#xff0c;艺术字更加美观有趣也更具有辨识度&#xff0c;常见于一些设计精美的杂志或宣传海报中。我们在日常工作中编辑Word文档时&#xff0c;也可以通过添加艺术字体来凸显文章的重点,美化页面排版。这篇文章将介绍如何使用FreeSpire.Doc for Java在word文档…

AI校招程序员最高薪酬曝光!腾讯80万年薪领跑,还送北京户口

来源&#xff1a;100offer概要&#xff1a;如果说 2016 年是互联网 AI 领域井喷的元年&#xff0c;2017 年整个 AI 领域全面爆发&#xff0c;来潮汹涌的趋势相较 2016 年可以说是有过之而无不及。如果说 2016 年是互联网 AI 领域井喷的元年&#xff0c;2017 年整个 AI 领域全面…

集合对象-“块数据”操作--其实是同一对象引用

例如&#xff1a; Set set1 new HashSet(); set1.add( object1 ); set1.add( ... ); set1.add( objectn ); Set set2 new HashSet( set1 ); 或者 Set set3 new HashSet( set1 ); set3.addAll( set1 ); set2 与 set3 中存储的都是 set1 元素的 “引用” 代码如…

vscode php断点,VSCode中设置断点调试PHP(示例代码)

所需文件xampp 集成服务器(本文使用Apache2.4MySQLPHP7.4.3)vscodeXdebugphp-debug 插件配置Xdebug1. 下载Xdebug插件 (直接去 https://xdebug.org/download.php下载php对应版本的插件)如果不知道如何选取版本&#xff0c;则如下Step 1&#xff1a;获取本地php版本信息 (利用ph…

2017英国AI形势报告:认知鸿沟、新商业模式和当下的挑战

原作 David Kelnar MMC投资研究中心老大Root 编译自 MMC Venture量子位 出品 | 公众号 QbitAI来源&#xff1a;36氪概要&#xff1a;AI技术今年所获得媒体、资本极度的关注&#xff0c;短时间内已经给民众带来认知上剧烈的冲击&#xff1a;或是由未知产生恐惧&#xff0c;或是对…

仓储物流参考资料

一种集成化仓储管理系统研究 http://www.docin.com/p-47000094.html 基于单据流程管理的仓储管理系统的研究 http://articles.e-works.net.cn/BPM/Article65651.htm

accept标头 php,如何在PHP中读取任何请求标头

如何在PHP中读取任何请求标头我应该如何阅读PHP中的任何标题&#xff1f;例如&#xff0c;自定义标头&#xff1a;X-Requested-With。Sabya asked 2019-02-28T12:09:45Z14个解决方案349 votes$_SERVER[HTTP_X_REQUESTED_WITH]RFC3875,4.1.18&#xff1a;如果使用的协议是HTTP&a…

前百度首席科学家吴恩达携手富士康,要用人工智能升级制造业

来源&#xff1a;澎湃新闻概要&#xff1a;当地时间12月14日&#xff0c;吴恩达再一次通过英文自媒体平台Medium公布了自己的下一个创业项目——Landing.ai。作为人工智能领域里的明星科学家、斯坦福大学计算机系教授吴恩达&#xff08;Andrew Ng&#xff09;&#xff0c;离开百…

特殊SQL示例

ProductsData pd_num pd_type pd_statusSCS-1-00 SCS-1 0 SCS-1-002 SCS-1 0 SCS-2-001 SCS-2 0 SCS-2-001 SCS-2 1结果(num1 是pd_status0的个数&#xff0c;num1 是pd_status1的个数&#xff09;pd_type num1 num2scs-1 2…

php静态文件怎么生成器,[新姿势]我用过的静态站点生成器们

随着诸如github pages的静态托管服务&#xff0c;静态站点生成器在近年有了极大的发展&#xff0c;静态生成托管对托管环境要求低、维护简单、可配合版本控制&#xff0c;但又灵活多变&#xff0c;在程序员和geek群体中大有超越WordPress等动态博客程序的势头近年来个人也好项目…

腾讯AI Lab解析2017 NIPS三大研究方向,启动教授及学生合作项目

来源&#xff1a; 腾讯AI实验室概要&#xff1a;腾讯AI Lab去年4月成立&#xff0c;今年第二次参加NIPS&#xff0c;共有8篇文章被录取&#xff0c;含一篇口头报告&#xff08;Oral&#xff09;。在所有国内研究机构和高校中&#xff0c;录取论文数仅次于清华大学。NIPS被誉为机…

Jackson第一篇【JSON字符串、实体之间的相互转换】

来源&#xff1a;http://blog.csdn.net/songyongfeng/article/details/6932655 既然你看到这篇文章相信你已经了解JSON的好处了&#xff0c;那么废话不多说直接进入主题。 Jackson是java中众多json处理工具的一个&#xff0c;比起常见的Json-lib,Gson要快一些。 Jackson的官…

「自然语言处理」如何快速理解?有这篇文章就够了!

原文来源&#xff1a;codeburst.io作者&#xff1a;Pramod Chandrayan「雷克世界」编译&#xff1a;嗯~阿童木呀、我是卡布达现如今&#xff0c;在更多情况下&#xff0c;我们是以比特和字节为生&#xff0c;而不是依靠交换情感。我们使用一种称之为计算机的超级智能机器在互联…

another mysql daemon,[守护进程详解及创建,daemon()使用

一&#xff0c;守护进程概述Linux Daemon(守护进程)是运行在后台的一种特殊进程。它独立于控制终端并且周期性地执行某种任务或等待处理某些发生的事件。它不需要用户输入就能运行而且提供某种服务&#xff0c;不是对整个系统就是对某个用户程序提供服务。Linux系统的大多数服务…

Jackson第二篇【从JSON字符串中取值】

来源&#xff1a;http://blog.csdn.net/songyongfeng/article/details/6932674 第一篇咱们主要学习了实体与json的相互转换的问题&#xff0c;但是咱们需要的是数据 你转换18遍我取不到数据也是扯淡&#xff0c;那么今天咱们就一起学习一下如何从使用Jackson从Json字符串中取值…

李开复:明年会有一批AI公司倒闭

来源&#xff1a;公众号黑智概要&#xff1a;在北美的四大AI巨头公司中&#xff0c;李开复的总结是&#xff1a;Google有大牛优势&#xff1b;Facebook做得更深&#xff0c;但没有平台化意识&#xff1b;微软在试着聚拢自己的实力&#xff1b;“四大AI公司中&#xff0c;有3家不…

java 多线程统计质数,Java 七 多线程计算某个范围内的质数

Java 7 多线程计算某个范围内的质数不多说了,看代码通用类package java7.concurrency.math;/*** This class generates prime numbers until is interrupted*/public class PrimeGenerator extends Thread{private long numberRange;public PrimeGenerator(long numberRange) {…