浅谈downpour
说起这个downpour,它就是一个拦截器的aop,它本身是一段代码,可以通过定义"切入点",来指定拦截器的代码在"切入点"的前后执行,从而起到拦截器的作用(
问题集中解决,避免重复代码。这也是我们编程的重要思想),
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; }
拦截器与过滤器的异同?
相同点:都可以在用户访问之前,执行一系列操作。
不同点:
1. Filter过滤器可以用来过滤(所有的请求(jsp\servlet\action等));拦截器只能用来拦截action;
2. Filter只能拦截到请求,不能具体到某一个方法。拦截器可以具体到方法名。
如何使用拦截器?
步骤: 创建一个拦截器的类(必须继承:AbstractInterceptor(没有具体到方法)、MethodFilterInterceptor(可以具体到方法))。 重写系统中的方法。 在struts.xml中配置拦截器。 <interceptors> <interceptor name=”拦截器名” class=”类” /> </interceptors> 注:必须是package中的第一行 在需要拦截的action中引用指定的拦截器名。 <action ………> <interceptor-ref name=”拦截器名” /> </action>
注:如果用户自定义了拦截器,系统将不会默认执行默认拦截操作。
<!-- 配置好一个拦截器 --> <interceptors> <interceptor name="firstInter" class="com.zuxia.interceptor.FirstInterceptor" /> <interceptor name="secondInter" class="com.zuxia.interceptor.SecondMethodInterceptor"> <param name="includeMethods">execute,add</param> </interceptor> <!-- 配置一个拦截器的链,并且设置为默认 --> <interceptor-stack name="myDefaultStack"> <interceptor-ref name="secondInter" /> <interceptor-ref name="defaultStack" /> </interceptor-stack> </interceptors> <!-- 设置系统默认引用的拦截器 --> <default-interceptor-ref name="myDefaultStack" />