- 浏览: 65435 次
- 性别:
- 来自: 北京
-
最新评论
-
wucaifang819787:
你好!麻烦问下不知道哪个图片行不行的:http://dl.it ...
struts2源码浅析(四) -
ChenXzh:
高手,佩服得五体投地
关于struts2报There is no Action mapped for namespace / and action name xxx_xxx
接上一篇讲了filter后,现在request到了action内了。
//Load Action class for mapping and invoke the appropriate Action method, or go directly to the Result. public void serviceAction(HttpServletRequest request, HttpServletResponse response, ServletContext context, ActionMapping mapping) throws ServletException { //createContextMap方法主要把Application、Session、Request的key value值拷贝到Map中 Map<String, Object> extraContext = createContextMap(request, response, mapping, context); // If there was a previous value stack, then create a new copy and pass it in to be used by the new Action ValueStack stack = (ValueStack) request.getAttribute(ServletActionContext.STRUTS_VALUESTACK_KEY); boolean nullStack = stack == null; if (nullStack) { ActionContext ctx = ActionContext.getContext(); if (ctx != null) { stack = ctx.getValueStack(); } } if (stack != null) { extraContext.put(ActionContext.VALUE_STACK, valueStackFactory.createValueStack(stack)); } String timerKey = "Handling request from Dispatcher"; try { UtilTimerStack.push(timerKey); String namespace = mapping.getNamespace(); String name = mapping.getName(); String method = mapping.getMethod(); Configuration config = configurationManager.getConfiguration(); //创建一个Action的代理对象,ActionProxyFactory是创建ActionProxy的工厂 //参考实现类:DefaultActionProxy和DefaultActionProxyFactory ActionProxy proxy = config.getContainer().getInstance(ActionProxyFactory.class).createActionProxy( namespace, name, method, extraContext, true, false); request.setAttribute(ServletActionContext.STRUTS_VALUESTACK_KEY, proxy.getInvocation().getStack()); // if the ActionMapping says to go straight to a result, do it! //如果是Result,则直接转向,关于Result,ActionProxy,ActionInvocation下一讲中再分析 if (mapping.getResult() != null) { Result result = mapping.getResult(); result.execute(proxy.getInvocation()); } else { //执行Action proxy.execute(); } // If there was a previous value stack then set it back onto the request if (!nullStack) { request.setAttribute(ServletActionContext.STRUTS_VALUESTACK_KEY, stack); } } catch (ConfigurationException e) { // WW-2874 Only log error if in devMode if(devMode) { LOG.error("Could not find action or result", e); } else { LOG.warn("Could not find action or result", e); } sendError(request, response, context, HttpServletResponse.SC_NOT_FOUND, e); } catch (Exception e) { sendError(request, response, context, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e); } finally { UtilTimerStack.pop(timerKey); } }
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; }
执行action时,要通过一系列拦截器的拦截,这也是struts2的一大特色。
拦截器中的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; }
这样,经过拦截器拦截,action调用业务code,返回result,再处理result交予前端,一个request的处理也告一段落。
附图一张,是关于action开始执行到处理返回result的整个过程。
结语:
发文数量不多,不怎么会写这样子的文章,造成了文字很少,代码很多,图也画的不甚专业,大家多多包涵。
入行时间不久,看源码难免有遗漏,错误的地方,还请大家多多指教。
评论

不知道哪个图片行不行的:http://dl.iteye.com/upload/picture/pic/129620/7557b68c-460b-393f-b427-d0f04e5f1b50.png这个地址可以看的到的,有时间麻烦看下。
发表评论
-
JAVA多线程-厕所问题
2012-11-22 11:55 2030在http://my.oschina.net/xpbug/bl ... -
第八章 最大自序列和
2012-11-01 20:29 945第八章的问题是常见的---最大自序列和 的问题 书中提 ... -
第二章 旋转字符串的思考
2012-10-26 16:09 914编程珠玑第二章旋转字符串,abcdefg向左旋转3位,变为de ... -
Mongdb的upsert出现E11000 duplicate key errors的错误分析
2012-10-25 17:36 9276昨日上线的系统,今天查日志时发现有不少E11000 dupli ... -
开源的Mongodb java client -- mango发布
2012-07-20 21:53 1899Mango ---- 一个非常简单的操作mongodb的 ... -
SOAP消息
2012-03-05 20:37 1298本文转自:http://blog.csdn.net/chang ... -
wsdl文档结构
2012-03-05 20:32 1579本文转自:http://blog.csdn.net/chang ... -
浅出Apache Cxf
2012-03-05 20:14 0由于业务需要,开放了系统的 Web Se ... -
struts2源码浅析(三)
2011-10-19 16:50 1633接上篇http://mazhiyuan.iteye.com/b ... -
struts2源码浅析(二)
2011-10-19 16:34 2322接上一篇http://mazhiyuan.iteye.com/ ... -
struts2源码浅析(一)
2011-10-19 16:18 18131. Struts2架构图 请求首先通过Filter ... -
struts2.1权威指南-笔记
2010-12-19 22:36 11501.struts 1.x 和 struts 2.x的� ... -
Hibernate学习总结4---对象状态
2010-12-10 16:14 1021session 的几个主要方法: 1,save方法和persi ... -
Hibernate学习总结3 --配置文件
2010-12-10 16:10 1041如果不希望使用默认的hibernate.cfg.xml 文件作 ... -
Hibernate 学习总结一
2010-12-10 14:54 934引入: 模型不匹配(阻 ... -
HF servlet&jsp 前6章要点总结
2010-11-21 11:58 972今天有时间把前6章主要讲servlet的内容坐下总结。好了,开 ... -
jquery源码分析之属性篇
2010-11-20 20:09 2025jquery提供了一些快捷函� ... -
HF servelt&jsp 定制标记开发 要点总结
2010-11-13 11:41 13831.标记文件使用一个页� ... -
bean相关标准动作总结+复习
2010-11-07 23:22 8211.<jsp:useBean>动作会定义一个变量, ... -
HF servlet&jsp ---include 指令和动作元素
2010-11-07 23:02 8581.include的2种方式 include多用于网站中可重用 ...
相关推荐
玻璃耐压测试设备sw23_三维3D设计图纸_三维3D设计图纸.zip
(DOC) 土木工程施工管理控制毕业论文 毕业设计.doc
内容概要:本文详细介绍了在MATLAB环境中利用随机子空间法(SSI)进行结构模态参数识别的方法,具体分为数据驱动(SSI-DATA)和协方差驱动(SSI-COV)两种方式。首先,通过对振动响应数据的预处理,如去除趋势项,确保数据的清洁。接着,分别阐述了这两种方法的具体实现步骤,包括构建Hankel矩阵、进行SVD分解以及投影运算等关键技术。同时,文章还提供了具体的MATLAB代码片段,帮助读者更好地理解和应用这些方法。此外,针对实际应用中的常见问题,如采样率设置不当、阶次选择困难等,给出了详细的解决方案和注意事项。 适合人群:从事结构健康监测、振动分析等相关领域的研究人员和技术人员,尤其是有一定MATLAB编程基础的用户。 使用场景及目标:适用于桥梁、建筑、机械设备等结构的模态参数识别,旨在提高结构健康监测的精度和效率。通过掌握这两种方法,可以更准确地获取结构的固有频率、阻尼比和振型等重要参数,为后续的结构评估和维护提供依据。 其他说明:文章强调了数据质量和预处理的重要性,并指出在实际应用中应结合稳定图等多种手段综合判断模态参数。同时提醒使用者在选择方法时要考虑具体应用场景的特点,如数据长度、噪声水平等因素。
(一级学科)攻读博士研究生培养方案 兰州大学土木工程与力学学院.doc
内容概要:本文详细介绍了主动油气悬架系统中PID控制和模糊控制的应用及其融合。首先解释了传统的PID控制原理,展示了其在应对复杂路况时的局限性。接着引入了模糊控制的概念,利用隶属度函数将自然语言转化为数学表达,从而更好地处理不确定性。最后提出了模糊PID控制器的设计思路,通过动态调整PID参数来提高系统的适应性和鲁棒性。实验结果显示,模糊PID控制器能够显著改善车辆行驶稳定性,特别是在非平整路面上。 适合人群:对汽车工程、控制系统设计感兴趣的工程师和技术爱好者。 使用场景及目标:适用于需要优化车辆悬架性能的研究和开发项目,旨在提高乘坐舒适性和操控稳定性。 其他说明:文中提供了多个Python代码片段作为示例,帮助读者理解和实现相关算法。此外还提到了一些实际应用中的挑战,如参数整定和执行器延迟等问题。
水流量传感器组装机sw20可编辑_三维3D设计图纸_三维3D设计图纸.zip
数据说明: 该数据集总共包含1028张轮胎图像。分为训练和测试数据,再分为裂纹(氧化)轮胎和正常轮胎。该数据可以用于二进制分类。
内容概要:本文详细介绍了利用扩展卡尔曼滤波(EKF)算法在Simulink环境中进行电池荷电状态(SOC)估计的方法及其优化过程。首先,作者选择并构建了一个二阶RC等效电路模型来模拟电池的行为,并引入了温度传感器模块以实现温度补偿。接着,通过分段线性插值方法调整电池容量,同时计算电流效率以提高SOC估算的准确性。然后,深入探讨了EKF算法的具体实现,包括状态预测和更新阶段的关键步骤。最后,展示了仿真的结果,验证了该方法的有效性,最大误差仅为0.4%。此外,文中还提供了许多实用的经验技巧,如OCV-SOC曲线的正确拟合方式、电流采样的处理以及参数的选择等。 适合人群:从事新能源汽车电池管理系统(BMS)研究与开发的技术人员,尤其是有一定MATLAB/Simulink基础的研究者。 使用场景及目标:适用于需要精确估计电池SOC的应用场合,旨在帮助工程师理解和掌握EKF算法在电池管理中的具体应用,从而优化电池性能监控系统的设计。 其他说明:文中不仅给出了详细的理论推导和技术细节,还分享了许多实际项目中的经验和注意事项,有助于读者更好地理解和应用所介绍的技术。
内容概要:本文详细介绍了多种常见的软件生命周期模型及其特点,包括瀑布模型、增量模型、敏捷模型、螺旋模型、原型模型、V模型、喷泉模型、RUP(统一过程)、极限编程(XP)等。每种模型都有其适用场景和独特优势。例如,瀑布模型适用于需求明确且稳定的项目,强调阶段顺序性和严格性;增量模型允许逐步增加功能,每次增量提供可运行的部分;敏捷模型强调快速响应变化,通过迭代和持续改进确保用户参与;螺旋模型结合了瀑布和增量模型的优点,特别适合处理不确定性和风险较大的项目;原型模型则适用于需求不明确的情况,通过快速构建原型获取用户反馈。此外,文中还介绍了Scrum框架、极限编程等具体实践方法,以及各模型在不同阶段的活动和交付物。 适合人群:本文适合对软件开发有一定了解的研发人员、项目经理及软件工程师,特别是那些希望深入了解不同软件生命周期模型的特点和应用场景的人士。 使用场景及目标:①帮助读者理解各种软件生命周期模型的优缺点;②指导项目团队根据项目需求选择合适的生命周期模型;③提供具体实践方法和工具,如Scrum框架、极限编程等,以提升项目管理和开发效率。 其他说明:本文不仅解释了各个模型的基本概念和适用条件,还通过对比分析帮助读者更好地理解和选择最适合的模型。对于希望优化项目流程、提高软件质量的团队来说,本文提供了宝贵的参考和指导。
2010注册勘察设计土木工程师(水利小电 工程地质)例题.doc
内容概要:本文详细介绍了如何利用Matlab和元胞自动机进行行人紧急疏散的模拟仿真。首先构建了一个20x30的二维网格房间模型,设置了出口、障碍物、行人和火灾源。通过三维矩阵记录每个单元格的状态,包括行人/障碍物、烟雾浓度和温度值。火灾扩散采用了热传导模型,考虑了材料燃烧特性,行人移动则基于动态场模型,结合出口吸引力、火灾排斥力和人群密度等因素。此外,还探讨了多层建筑的扩展方法,如引入楼梯单元和调整烟雾扩散规则。实验结果显示,当行人密度超过45%,出口处会出现“拱形堵塞”,烟雾能见度下降使疏散时间显著增加,设置中间避难区可有效降低伤亡率。 适合人群:对元胞自动机、Matlab编程以及紧急疏散模拟感兴趣的科研人员、学生和技术爱好者。 使用场景及目标:适用于研究复杂建筑环境中的紧急疏散策略,帮助优化建筑设计和应急响应措施,提高疏散效率和安全性。 其他说明:文中提供了详细的代码片段,涵盖了从环境初始化、火灾扩散、行人移动到可视化的完整流程。通过调整参数,可以观察不同的疏散现象,如拱形堵塞、路径切换等。
倍速链旋转台sw22_三维3D设计图纸.zip
长条插件机sw22可编辑_三维3D设计图纸_三维3D设计图纸.zip
aea2c-main.zip
金属400型连续挤压机step_三维3D设计图纸_三维3D设计图纸.zip
《土木工程概论》综合复习资料.doc
电磁领域系列仿真模拟教程,每个包10几个教程,从基础到精通,案例多多。
工作模板 -行动学习教练工具箱.doc
电磁领域系列仿真模拟教程,每个包10几个教程,从基础到精通,案例多多。
本文主要研究了一类时间分数阶偏微分方程的正问题与反问题。对于正问题,已知初始条件 u(x,0),通过求解带有左Caputo分数阶导数的非线性偏微分方程得到 u(x,1) 的精确解。对于反问题,已知 u(x,1),采用简化的准可逆正则化方法求解 u(x,0),并给出了相对误差水平(REL)和绝对误差水平(AEL)的计算公式。文中还介绍了离散格式下的时间和空间导数近似方法,并证明了关于正则化参数选择的一个引理。