- 浏览: 21109 次
- 性别:
- 来自: 上海
最新评论
-
liangfuming:
看了之后受益匪浅
Struts2 -- ActionProxy&ActionInvocation -
nianien:
你好,我怎么找不到哪个地方有写加载struts.propert ...
Struts2--Dispatcher&ConfigurationProvider
下面开始讲一下主菜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.
action执行完了,还要根据ResultConfig返回到view,也就是在invoke方法中调用executeResult方法。
最后看一张在网上看到的一个调用流程图作为参考:
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; }
最后看一张在网上看到的一个调用流程图作为参考:
发表评论
-
Struts2--ActionContext及CleanUP Filter
2010-10-26 16:41 16261. ActionContext ActionCont ... -
Struts2--Dispatcher&ConfigurationProvider
2010-10-26 16:39 973首先强调一下struts2的线程程安全,在Struts2中 ... -
Struts2--Dispatcher&ConfigurationProvider续
2010-10-26 16:36 1183接下来第三步:init_LegacyStrutsPrope ... -
Struts2 --FilterDispatcher核心控制器
2010-10-26 16:34 1749Dispatcher已经在之前讲过,这就好办了。Filte ... -
Struts2 --拦截器&工作流程概述
2010-10-24 01:00 2066记得一次面试当面试 ...
相关推荐
`ActionProxy`则负责创建并管理`ActionInvocation`实例。 2. **拦截器(Interceptors)**:Struts2的拦截器是其强大的特性之一,允许开发者在Action执行前后添加自定义逻辑。这些拦截器可以实现登录验证、日志记录...
Struts2是一个流行的Java web应用程序框架,用于构建MVC(模型-视图-控制器)架构的应用。源代码分析有助于深入理解其内部工作原理,优化应用性能,并进行自定义扩展。 1. **Struts2架构图** 请求在Struts2框架中...
`ActionInvocation`在Struts2框架中扮演着调度者的角色,负责整个Action执行过程的调度。它不仅负责调用Action的`execute`方法,还负责拦截器链的执行顺序,以及最终结果的处理。`ActionInvocation`通过调用拦截器链...
例如,`ActionInvocation`接口定义了执行Action的逻辑,而`ActionProxy`负责创建和管理Action实例。 2. **struts2-convention**: 这个模块支持约定优于配置(Convention over Configuration)的概念,允许开发者...
Struts2是一个流行的Java Web框架,它简化了MVC(模型-视图-控制器)架构的实现。在本文中,我们将深入探讨Struts2的工作原理和源码分析,以帮助理解其内在机制。 1. **Struts2架构图**: 当一个HTTP请求到达...
- Action执行完毕后,`ActionInvocation`根据Struts2配置文件中的结果配置,返回一个结果代码(例如`SUCCESS`或`ERROR`)。 - 根据结果代码,加载相应的视图模板(如JSP页面)进行渲染。 7. **拦截器后处理**: ...
### Xwork——Struts2核心 #### Xwork与Struts2的关系 Xwork作为Struts2的核心组件之一,它的设计理念和技术实现对整个Struts2框架起着决定性的作用。Struts2是一个流行的Java Web开发框架,它采用了MVC(Model-...
Struts2的核心组件包括:`ActionContextCleanUp`、`FilterDispatcher`、`ActionMapper`、`ActionProxy`、`ActionInvocation`以及相关的配置机制。本文将深入探讨这些核心组件的工作原理,并通过对Struts2请求处理...
### Struts2基础知识与实践 #### 一、为什么学习Struts2 - **提升编码效率**:Struts2提供了一套标准的MVC框架结构,能够帮助开发者快速地实现业务逻辑与视图分离,减少重复代码,从而提高开发效率。 - **框架特性...
基于STRUTS-2框架产品信息Web发布系统的实现 STRUTS 2 框架是 Apache Jakarta 项目组的一个 Open-Source 项目,是 MVC 模型的一个良好实现。MVC 模型把一个应用的输入、处理、输出流程按照 Model、View、...
### Struts2内核知识点详解 #### 一、Struts2概述 Struts2是一个基于MVC模式的开源Java Web应用框架,它继承了Struts1的一些设计理念,并且吸收了WebWork框架的优点,使得它在架构上更加灵活、强大。对于初学者来...
Struts2是一个强大的Java Web应用框架,它是基于Model-View-Controller(MVC)设计模式的,用于构建可扩展的企业级应用。Struts2的出现是由于WebWork和Struts社区的合并,它继承了两者的优势,提供了更高效、灵活的...
- **ActionProxy**: 在Struts2中扮演着中介的角色,它根据配置信息来定位并创建具体的Action实例,并将其委托给`ActionInvocation`进行执行。 - **ActionInvocation**: 负责实际的Action调用过程,同时处理拦截器的...
深入理解Struts2的核心源码,有助于掌握其内部工作原理,如ActionInvocation的执行流程,以及拦截器链的处理。 七、Struts2整合 Struts2可以与其他技术无缝集成,如: - **JSF**: 结合JavaServer Faces,提高组件化...
Struts2是一个流行的Java Web开发框架,它遵循MVC(模型-视图-控制器)设计模式,用于构建可维护性和可扩展性高的Web应用程序。在深入理解Struts2的工作流程之前,我们需要先了解一些基本概念。 1. **MVC模式**: ...
### Struts2自学文档知识点详解 #### 一、Struts2简介 Struts2是一个用于构建企业级Java Web应用程序的开源框架。它基于MVC(Model-View-Controller)架构模式,提供了一种灵活的方式来组织代码,使得业务逻辑、...
Struts2 面试题 Struts2 是基于 Java 语言的 Web 应用程序框架,继承自 WebWork 框架。Struts2 的主要特点是使用 FilterDispatcher 作为核心控制器,将请求分发到相应的 Action 中。下面是 Struts2 面试题中涉及到...