- 浏览: 893462 次
- 性别:
- 来自: 北京
文章分类
- 全部博客 (687)
- java (127)
- servlet (38)
- struts (16)
- spring (22)
- hibernate (40)
- javascript (58)
- jquery (18)
- tomcat (51)
- 设计模式 (6)
- EJB (13)
- jsp (3)
- oracle (29)
- RUP (2)
- ajax (3)
- java内存管理 (4)
- java线程 (12)
- socket (13)
- path (5)
- XML (10)
- swing (2)
- UML (1)
- JBPM (2)
- 开发笔记 (45)
- Note参考 (15)
- JAXB (4)
- Quartz (2)
- 乱码 (2)
- CSS (2)
- Exception (4)
- Tools (7)
- sqlserver (3)
- DWR (7)
- Struts2 (47)
- WebService (2)
- 问题解决收藏 (7)
- JBOSS (7)
- cache (10)
- easyUI (19)
- jQuery Plugin (11)
- FreeMarker (6)
- Eclipse (2)
- Compass (2)
- JPA (1)
- WebLogic (1)
- powerdesigner (1)
- mybatis (1)
最新评论
-
bugyun:
受教了,谢谢
java 正则表达式 过滤html标签 -
xiongxingxing_123:
学习了,感谢了
java 正则表达式 过滤html标签 -
wanmeinange:
那如果无状态的。对同一个任务并发控制怎么做?比如继承Quart ...
quartz中参数misfireThreshold的详解 -
fanjieshanghai:
...
XPath 元素及属性查找 -
tianhandigeng:
还是没明白
quartz中参数misfireThreshold的详解
专栏地址:http://www.iteye.com/wiki/struts2/1397-deep-into-struts2-interceptors
在之前的文章中,我们已经涉及到了拦截器(Interceptor)的概念。
接下来,我们将重点讨论一下Struts2中的拦截器的内部结构和执行顺序,并结合源码进行分析。
Interceptor结构
让我们再来回顾一下之前我们曾经用过的一张Action LifeCycle的图:
图中,我们可以发现,Struts2的Interceptor一层一层,把Action包裹在最里面。这样的结构,大概有以下一些特点:
1. 整个结构就如同一个堆栈,除了Action以外,堆栈中的其他元素是Interceptor
2. Action位于堆栈的底部。由于堆栈"先进后出"的特性,如果我们试图把Action拿出来执行,我们必须首先把位于Action上端的Interceptor拿出来执行。这样,整个执行就形成了一个递归调用
3. 每个位于堆栈中的Interceptor,除了需要完成它自身的逻辑,还需要完成一个特殊的执行职责。这个执行职责有3种选择:
1) 中止整个执行,直接返回一个字符串作为resultCode
2) 通过递归调用负责调用堆栈中下一个Interceptor的执行
3) 如果在堆栈内已经不存在任何的Interceptor,调用Action
Struts2的拦截器结构的设计,实际上是一个典型的责任链模式的应用。首先将整个执行划分成若干相同类型的元素,每个元素具备不同的逻辑责任,并将他们纳入到一个链式的数据结构中(我们可以把堆栈结构也看作是一个递归的链式结构),而每个元素又有责任负责链式结构中下一个元素的执行调用。
这样的设计,从代码重构的角度来看,实际上是将一个复杂的系统,分而治之,从而使得每个部分的逻辑能够高度重用并具备高度可扩展性。所以,Interceptor结构实在是Struts2/Xwork设计中的精华之笔。
Interceptor执行分析
Interceptor的定义
我们来看一下Interceptor的接口的定义:
- public interface Interceptor extends Serializable {
- /**
- * Called to let an interceptor clean up any resources it has allocated.
- */
- void destroy();
- /**
- * Called after an interceptor is created, but before any requests are processed using
- * {@link #intercept(com.opensymphony.xwork2.ActionInvocation) intercept} , giving
- * the Interceptor a chance to initialize any needed resources.
- */
- void init();
- /**
- * Allows the Interceptor to do some processing on the request before and/or after the rest of the processing of the
- * request by the {@link ActionInvocation} or to short-circuit the processing and just return a String return code.
- *
- * @return the return code, either returned from {@link ActionInvocation#invoke()}, or from the interceptor itself.
- * @throws Exception any system-level error, as defined in {@link com.opensymphony.xwork2.Action#execute()}.
- */
- String intercept(ActionInvocation invocation) throws Exception;
- }
public interface Interceptor extends Serializable { /** * Called to let an interceptor clean up any resources it has allocated. */ void destroy(); /** * Called after an interceptor is created, but before any requests are processed using * {@link #intercept(com.opensymphony.xwork2.ActionInvocation) intercept} , giving * the Interceptor a chance to initialize any needed resources. */ void init(); /** * Allows the Interceptor to do some processing on the request before and/or after the rest of the processing of the * request by the {@link ActionInvocation} or to short-circuit the processing and just return a String return code. * * @return the return code, either returned from {@link ActionInvocation#invoke()}, or from the interceptor itself. * @throws Exception any system-level error, as defined in {@link com.opensymphony.xwork2.Action#execute()}. */ String intercept(ActionInvocation invocation) throws Exception; }
Interceptor的接口定义没有什么特别的地方,除了init和destory方法以外,intercept方法是实现整个拦截器机制的核心方法。而它所依赖的参数ActionInvocation则是我们之前章节中曾经提到过的著名的Action调度者。
我们再来看看一个典型的Interceptor的抽象实现类:
- public abstract class AroundInterceptor extends AbstractInterceptor {
- /* (non-Javadoc)
- * @see com.opensymphony.xwork2.interceptor.AbstractInterceptor#intercept(com.opensymphony.xwork2.ActionInvocation)
- */
- @Override
- public String intercept(ActionInvocation invocation) throws Exception {
- String result = null;
- before(invocation);
- // 调用下一个拦截器,如果拦截器不存在,则执行Action
- result = invocation.invoke();
- after(invocation, result);
- return result;
- }
- public abstract void before(ActionInvocation invocation) throws Exception;
- public abstract void after(ActionInvocation invocation, String resultCode) throws Exception;
- }
public abstract class AroundInterceptor extends AbstractInterceptor { /* (non-Javadoc) * @see com.opensymphony.xwork2.interceptor.AbstractInterceptor#intercept(com.opensymphony.xwork2.ActionInvocation) */ @Override public String intercept(ActionInvocation invocation) throws Exception { String result = null; before(invocation); // 调用下一个拦截器,如果拦截器不存在,则执行Action result = invocation.invoke(); after(invocation, result); return result; } public abstract void before(ActionInvocation invocation) throws Exception; public abstract void after(ActionInvocation invocation, String resultCode) throws Exception; }
在这个实现类中,实际上已经实现了最简单的拦截器的雏形。或许大家对这样的代码还比较陌生,这没有关系。我在这里需要指出的是一个很重要的方法invocation.invoke()。这是ActionInvocation中的方法,而ActionInvocation是Action调度者,所以这个方法具备以下2层含义:
1. 如果拦截器堆栈中还有其他的Interceptor,那么invocation.invoke()将调用堆栈中下一个Interceptor的执行。
2. 如果拦截器堆栈中只有Action了,那么invocation.invoke()将调用Action执行。
所以,我们可以发现,invocation.invoke()这个方法其实是整个拦截器框架的实现核心。基于这样的实现机制,我们还可以得到下面2个非常重要的推论:
1. 如果在拦截器中,我们不使用invocation.invoke()来完成堆栈中下一个元素的调用,而是直接返回一个字符串作为执行结果,那么整个执行将被中止。
2. 我们可以以invocation.invoke()为界,将拦截器中的代码分成2个部分,在invocation.invoke()之前的代码,将会在Action之前被依次执行,而在invocation.invoke()之后的代码,将会在Action之后被逆序执行。
由此,我们就可以通过invocation.invoke()作为Action代码真正的拦截点,从而实现AOP。
Interceptor拦截类型
从上面的分析,我们知道,整个拦截器的核心部分是invocation.invoke()这个函数的调用位置。事实上,我们也正式根据这句代码的调用位置,来进行拦截类型的区分的。在Struts2中,Interceptor的拦截类型,分成以下三类:
1. before
before拦截,是指在拦截器中定义的代码,它们存在于invocation.invoke()代码执行之前。这些代码,将依照拦截器定义的顺序,顺序执行。
2. after
after拦截,是指在拦截器中定义的代码,它们存在于invocation.invoke()代码执行之后。这些代码,将一招拦截器定义的顺序,逆序执行。
3. PreResultListener
有的时候,before拦截和after拦截对我们来说是不够的,因为我们需要在Action执行完之后,但是还没有回到视图层之前,做一些事情。Struts2同样支持这样的拦截,这种拦截方式,是通过在拦截器中注册一个PreResultListener的接口来实现的。
- public interface PreResultListener {
- /**
- * This callback method will be called after the Action execution and before the Result execution.
- *
- * @param invocation
- * @param resultCode
- */
- void beforeResult(ActionInvocation invocation, String resultCode);
- }
public interface PreResultListener { /** * This callback method will be called after the Action execution and before the Result execution. * * @param invocation * @param resultCode */ void beforeResult(ActionInvocation invocation, String resultCode); }
在这里,我们看到,Struts2能够支持如此多的拦截类型,与其本身的数据结构和整体设计有很大的关系。正如我在之前的文章中所提到的:
我们可以看到,Struts2对于整个执行的划分,从Interceptor到Action一直到Result,每一层都职责明确。不仅如此,Struts2还为每一个层次之前都设立了恰如其分的插入点。使得整个Action层的扩展性得到了史无前例的提升。
Interceptor执行顺序
Interceptor的执行顺序或许是我们在整个过程中最最关心的部分。根据上面所提到的概念,我们实际上已经能够大致明白了Interceptor的执行机理。我们来看看Struts2的Reference对Interceptor执行顺序的一个形象的例子。
如果我们有一个interceptor-stack的定义如下:
- <interceptor-stack name="xaStack">
- <interceptor-ref name="thisWillRunFirstInterceptor"/>
- <interceptor-ref name="thisWillRunNextInterceptor"/>
- <interceptor-ref name="followedByThisInterceptor"/>
- <interceptor-ref name="thisWillRunLastInterceptor"/>
- </interceptor-stack>
<interceptor-stack name="xaStack"> <interceptor-ref name="thisWillRunFirstInterceptor"/> <interceptor-ref name="thisWillRunNextInterceptor"/> <interceptor-ref name="followedByThisInterceptor"/> <interceptor-ref name="thisWillRunLastInterceptor"/> </interceptor-stack>
那么,整个执行的顺序大概像这样:
在这里,我稍微改了一下Struts2的Reference中的执行顺序示例,使得整个执行顺序更加能够被理解。我们可以看到,递归调用保证了各种各样的拦截类型的执行能够井井有条。
请注意在这里,每个拦截器中的代码的执行顺序,在Action之前,拦截器的执行顺序与堆栈中定义的一致;而在Action和Result之后,拦截器的执行顺序与堆栈中定义的顺序相反。
源码解析
接下来我们就来看看源码,看看Struts2是如何保证拦截器、Action与Result三者之间的执行顺序的。
之前我曾经提到,ActionInvocation是Struts2中的调度器,所以事实上,这些代码的调度执行,是在ActionInvocation的实现类中完成的,这里,我抽取了DefaultActionInvocation中的invoke()方法,它将向我们展示一切。
- /**
- * @throws ConfigurationException If no result can be found with the returned code
- */
- public String invoke() throws Exception {
- String profileKey = "invoke: ";
- try {
- UtilTimerStack.push(profileKey);
- if (executed) {
- throw new IllegalStateException("Action has already executed");
- }
- // 依次调用拦截器堆栈中的拦截器代码执行
- if (interceptors.hasNext()) {
- final InterceptorMapping interceptor = (InterceptorMapping) interceptors.next();
- UtilTimerStack.profile("interceptor: "+interceptor.getName(),
- new UtilTimerStack.ProfilingBlock<String>() {
- public String doProfiling() throws Exception {
- // 将ActionInvocation作为参数,调用interceptor中的intercept方法执行
- resultCode = interceptor.getInterceptor().intercept(DefaultActionInvocation.this);
- return null;
- }
- });
- } else {
- 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
- if (!executed) {
- // 执行PreResultListener
- if (preResultListeners != null) {
- for (Iterator iterator = preResultListeners.iterator();
- iterator.hasNext();) {
- PreResultListener listener = (PreResultListener) iterator.next();
- String _profileKey="preResultListener: ";
- try {
- UtilTimerStack.push(_profileKey);
- listener.beforeResult(this, resultCode);
- }
- finally {
- UtilTimerStack.pop(_profileKey);
- }
- }
- }
- // now execute the result, if we're supposed to
- // action与interceptor执行完毕,执行Result
- if (proxy.getExecuteResult()) {
- executeResult();
- }
- executed = true;
- }
- return resultCode;
- }
- finally {
- UtilTimerStack.pop(profileKey);
- }
- }
/** * @throws ConfigurationException If no result can be found with the returned code */ public String invoke() throws Exception { String profileKey = "invoke: "; try { UtilTimerStack.push(profileKey); if (executed) { throw new IllegalStateException("Action has already executed"); } // 依次调用拦截器堆栈中的拦截器代码执行 if (interceptors.hasNext()) { final InterceptorMapping interceptor = (InterceptorMapping) interceptors.next(); UtilTimerStack.profile("interceptor: "+interceptor.getName(), new UtilTimerStack.ProfilingBlock<String>() { public String doProfiling() throws Exception { // 将ActionInvocation作为参数,调用interceptor中的intercept方法执行 resultCode = interceptor.getInterceptor().intercept(DefaultActionInvocation.this); return null; } }); } else { 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 if (!executed) { // 执行PreResultListener if (preResultListeners != null) { for (Iterator iterator = preResultListeners.iterator(); iterator.hasNext();) { PreResultListener listener = (PreResultListener) iterator.next(); String _profileKey="preResultListener: "; try { UtilTimerStack.push(_profileKey); listener.beforeResult(this, resultCode); } finally { UtilTimerStack.pop(_profileKey); } } } // now execute the result, if we're supposed to // action与interceptor执行完毕,执行Result if (proxy.getExecuteResult()) { executeResult(); } executed = true; } return resultCode; } finally { UtilTimerStack.pop(profileKey); } }
从源码中,我们可以看到,我们之前提到的Struts2的Action层的4个不同的层次,在这个方法中都有体现,他们分别是:拦截器(Interceptor)、Action、PreResultListener和Result。在这个方法中,保证了这些层次的有序调用和执行。由此我们也可以看出Struts2在Action层次设计上的众多考虑,每个层次都具备了高度的扩展性和插入点,使得程序员可以在任何喜欢的层次加入自己的实现机制改变Action的行为。
在这里,需要特别强调的,是其中拦截器部分的执行调用:
resultCode = interceptor.getInterceptor().intercept(DefaultActionInvocation.this);
表面上,它只是执行了拦截器中的intercept方法,如果我们结合拦截器来看,就能看出点端倪来:
- public String intercept(ActionInvocation invocation) throws Exception {
- String result = null;
- before(invocation);
- // 调用invocation的invoke()方法,在这里形成了递归调用
- result = invocation.invoke();
- after(invocation, result);
- return result;
- }
public String intercept(ActionInvocation invocation) throws Exception { String result = null; before(invocation); // 调用invocation的invoke()方法,在这里形成了递归调用 result = invocation.invoke(); after(invocation, result); return result; }
原来在intercept()方法又对ActionInvocation的invoke()方法进行递归调用,ActionInvocation循环嵌套在intercept()中,一直到语句result = invocation.invoke()执行结束。这样,Interceptor又会按照刚开始执行的逆向顺序依次执行结束。
一个有序链表,通过递归调用,变成了一个堆栈执行过程,将一段有序执行的代码变成了2段执行顺序完全相反的代码过程,从而巧妙地实现了AOP。这也就成为了Struts2的Action层的AOP基础。
发表评论
-
ognl表达式
2011-07-07 00:36 1301OGNL是Object Graphic Navigation ... -
在Struts 2_0中实现表单数据校验
2011-07-07 00:02 1147转换与校验(Conversion & Validati ... -
简单的struts2输入校验框架
2011-05-13 23:43 10901.输入页面login.jsp: <%@ page ... -
struts2在学习(十二)--表单验证的两种方式
2011-05-13 23:13 960第四个示例:注解方式校验器---用户注册页面user2_reg ... -
struts2在学习(十一)--表单验证的两种方式
2011-05-13 23:09 909第二个示例:XML配置式校验器---登录和注册页面user_l ... -
struts2在学习(十)--表单验证的两种方式
2011-05-13 22:56 11661. Struts2中的输入校验2. 编码方式校验 1) A ... -
struts2采用convention-plugin实现零配置
2011-05-13 21:58 1120最近开始关注struts2的新特性,从这个版本开始,Strut ... -
基于SSH2框架Struts2拦截器的登录验证实现
2011-04-01 22:00 2293通过之前的Struts2.1.6+Spring2.5.6+H ... -
通过ActionContext类访问Servlet对象
2011-04-01 21:40 1924ActionContext类位于com.opensympho ... -
webwork 之销毁session
2011-04-01 17:35 1773销毁的意思?不是清空 ... -
Struts2 Convention Plugin(三)
2011-03-18 01:26 1206Annotation 参考Convention使用某些注解语句 ... -
Struts2 Convention Plugin(二)
2011-03-18 01:25 1155Results and result codesStruts ... -
Struts2 Convention Plugin(一)
2011-03-18 01:25 1105Introduction从struts2.1版本开始,Conv ... -
struts2页面中的标签调用类的方法
2011-03-15 16:33 1624<s:set name="str" ... -
Apache Struts 2.2.1 GA版发布
2011-03-14 17:14 1339昨日,Apache软件基金会发布了Struts 2.2.1 G ... -
spring2 +hibernate 3 + struts 配置
2011-03-14 15:15 12191. web.xml 1. <?xml versi ... -
Struts2 中action之间的跳转
2011-03-14 12:32 1258转载于http://zhou568xiao.iteye.com ... -
Struts2 的Result Type
2011-03-13 16:35 1050http://www.blogjava.net/duanzhi ... -
struts2 跳转类型 result type=chain、dispatcher、redirect(redirect-action)
2011-03-13 16:32 1627dispatcher 为默认跳转类型,用于返回一个视图资源(如 ... -
struts2防止重复提交
2011-03-10 23:07 1296struts2的防止重复提交 也使用到了 token (令牌机 ...
相关推荐
### Struts2拦截器详解 #### 一、Struts2拦截器概述 Struts2框架作为Java Web开发中的一种流行框架,其核心组件之一便是**拦截器**。拦截器不仅在Struts2中扮演着重要角色,更是整个框架灵活性与扩展性的基石。...
在Struts2中,拦截器(Interceptors)扮演着核心角色,增强了框架的功能和灵活性。这篇文章将深入探讨Struts2拦截器的概念、工作原理以及如何在实际应用中使用它们。 **一、什么是Struts2拦截器** 拦截器是基于AOP...
Struts 2是Java Web开发中的一个开源框架,它的核心机制之一就是拦截器(Interceptor)。拦截器在MVC模式中扮演着重要的角色,允许开发者在请求处理前后插入自定义的逻辑,增强了系统的可扩展性和灵活性。 ### 拦截...
拦截器是Struts2的核心组件之一,它基于AOP(面向切面编程)的概念,为框架提供了高度的灵活性和可扩展性。以下是关于Struts2拦截器的基础知识的详细说明: 1. **拦截器的定义与作用**: - 拦截器是Struts2框架中...
Struts2拦截器(Interceptor) Struts2拦截器(Interceptor)
总结起来,这个"Struts拦截器案例——登陆"涵盖了Struts2拦截器的基本使用、登录验证、数据库操作以及异常处理等多个方面。通过学习这个案例,开发者可以更好地理解和掌握Struts2框架中的拦截器机制,从而在实际项目...
在本学习案例中,重点在于Struts2的拦截器(Interceptor)功能,这是Struts2的核心特性之一,它允许开发者在Action执行前后进行自定义处理,实现了灵活的业务逻辑控制和增强的功能。 首先,我们来理解一下什么是...
这个“struts2——docs部分”很显然是Struts2官方文档或者相关的技术资料集合,通常包含详细的框架介绍、API参考、用户指南、教程等内容。在深入学习Struts2时,这些文档是非常重要的参考资料。 **1. 框架概述** ...
在Struts2框架中,拦截器扮演着关键角色,它们提供了AOP(面向切面编程)的功能,使得开发者可以在不修改业务逻辑的情况下,对请求处理流程进行增强。本文将深入探讨Struts2的拦截器使用,结合实例和源码分析,帮助...
解决Struts2中的中文乱码。该代码是用作Struts2的拦截器中
本文将深入探讨如何使用Struts2实现拦截器,以及如何配置拦截器来实现用户权限拦截。 首先,我们需要了解拦截器的工作原理。在Struts2中,拦截器是基于Java的动态代理机制实现的,它们按照预定义的顺序形成一个拦截...
2. **拦截器链**:在Struts2中,多个拦截器可以形成一个拦截器链,每个拦截器按照定义的顺序依次执行。如果所有拦截器都允许Action执行,那么Action的结果将被传递到下一个拦截器,直到整个链执行完毕。 ### 二、...
在Struts2中,拦截器工作在Action和结果(Result)之间,形成一个拦截器栈,每个拦截器按照配置的顺序依次执行。 Struts2的拦截器执行流程如下: 1. **初始化拦截器栈**:当Struts2框架启动时,会根据配置文件...
首先,理解拦截器的定义:拦截器是AOP(面向切面编程)的一个概念,在Struts2中,拦截器是基于Java的动态代理机制实现的。它们是一系列实现了`Interceptor`接口的类,可以在Action执行前后插入额外的行为。这些行为...
在Struts2中,拦截器(Interceptor)扮演着至关重要的角色,它允许开发者在动作执行前后插入自定义逻辑,如日志记录、权限验证等。在本案例中,我们将深入探讨如何使用Struts2拦截器实现登录权限验证,同时结合...
struts2常用拦截器,struts2经常用到的拦截器,熟悉熟悉
当请求到达控制器时,Struts2会依次调用这个栈中的拦截器,每个拦截器都有机会处理请求,然后决定是否将请求传递给下一个拦截器或直接返回响应。 创建一个简单的Struts2拦截器,你需要遵循以下步骤: 1. 创建拦截...
在Struts2中,拦截器(Interceptor)扮演着核心角色,它们允许开发者在Action执行前后插入自定义的逻辑,如日志、权限检查、事务管理等。现在我们将深入探讨Struts2的拦截器机制及其实例应用。 ### 一、Struts2拦截...
拦截器(Interceptor)是Struts2的另一个重要组成部分,它允许在Action执行前后插入自定义逻辑,如日志记录、权限验证等。 三、MVC模式 在Struts2中,Model代表业务逻辑,View负责展示数据,Controller则协调Model...