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 领域全面…

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;或是对…

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

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

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

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

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

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

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

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

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

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

德勤预测2018年9大科技趋势:AR走进普通用户,直播仍然是王道

来源&#xff1a;腾讯科技编辑&#xff1a;Jennie“我们眼下正处在一个临界点&#xff0c;即机器学习将在企业市场加速普及&#xff0c;从而推动改进企业运营&#xff0c;让企业作出更好的决策&#xff0c;并提供增强或全新的产品和服务。”——德勤副总裁保罗萨罗米据外媒报道…

谷歌人工智能检索开普勒望远镜数据后,找到了“迷你太阳系”

“开普勒&#xff0d;90”和太阳系一样拥有八大行星 本文图片均来自 NASA来源&#xff1a;澎湃新闻概要&#xff1a;当地时间12月15日&#xff0c;美国国家航空航天局NASA宣布在“行星猎手”开普勒望远镜的数据库中找到了恒星“开普勒&#xff0d;90”周围的第八颗行星&#xf…

php去除所有标点符号的方法,php如何去除标点符号

php去除标点符号的方法&#xff1a;首先创建一个PHP示例文件&#xff1b;然后通过正则表达式“preg_replace($pattern, , $str);”删除字符串中的中英文标点符号即可。推荐&#xff1a;《PHP视频教程》php正则&#xff0c;删除字符串中的中英文标点符号原理很简单&#xff0c;…

美国的人工智能企业在研发哪些有趣的AI产品?

来源&#xff1a;亿欧概要&#xff1a;本文盘点了美国AI企业的有趣产品&#xff0c;或许能给国内AI创业者和投资人有所启发。同样是AI创业&#xff0c;国内外的打法显然不同。在国内&#xff0c;大部分AI创业公司都在拼主赛道&#xff0c;比如无人驾驶、AI安防、AI医疗、AI教育…

Java技术回顾之JNDI--实例

一、JNDI在Java EE中的应用JNDI 技术是Java EE规范中的一个重要“幕后”角色&#xff0c;它为Java EE容器、组件提供者和应用程序之间提供了桥梁作用&#xff1a;Java EE容器同时扮演JNDI提供者角色&#xff0c;组件提供者将某个服务的具体实现部署到容器上&#xff0c;应用程序…

【观点】智能制造:新时代智能产业革命的基石|王飞跃

来源&#xff1a; 中国科学院自动化研究所概要&#xff1a;以新的理念和新的技术发展新时期的智能制造科技&#xff0c;创新智能产业革命&#xff0c;将是中国从制造大国到制造强国&#xff0c;进而从世界大国到世界强国的必由之道和开路先锋。实体经济&#xff0c;特别是以制造…

matlab连续型随机变量,matlab连续型随机变量的分布.doc

matlab连续型随机变量的分布.doc 连续型随机变量的分布及其数字特征一、基本概念设随机变量X的分布函数为F(x)&#xff0c;若存在非负函数f(x)&#xff0c;使对任意实数x&#xff0c;有≤X{Pxd}则称X为连续型随机变量&#xff0c;并称f(x)为X的概率密度&#xff0c;它满…

CB Insights发布AI创业公司100榜单 ,7家中国公司上榜,两家二次登榜

来源&#xff1a;36氪概要&#xff1a;近日&#xff0c;硅谷知名数据公司 CB Insights 在美国旧金山发布了第二届全球最强 AI 创业公司榜单AI 100。旷视科技、出门问问、今日头条、英语流利说、优必选、商汤科技以及寒武纪上榜 。近日&#xff0c;硅谷知名数据公司 CB Insights…