在Struts中,拦截器可以在Action执行之前或之后被调用。Struts2框架的大多数核心功能都是作为拦截器来实现的。
例如为action动态的添加
输入验证(验证用户输入的是否正确)
对象组装(将用户输入的数据转换为对象的属性)
权限控制(如访问者为登录用户)
日志记录(记录action的执行情况)
这些操作都可以通过拦截器实现,而不用修改action
拦截器的工作流程如图:
如图,在接收到请求后,先顺序通过各种拦截器,如果没有被拦截,则执行Action类处理请求,处理完成后,逆序通过拦截器(正来反回,像栈一样)。
下面通过一个java项目来模拟拦截器的工作时序
1.建立如下图的项目目录结构
2.Action类代码:(模拟框架中的Action)
public class Action {
public void execute() {
System.out.println("execute!");
}
}
3.写一个拦截器接口然后写两个拦截器类,模拟拦截器
public interface Interceptor {
public void intercept(ActionInvocation invocation);
}
public class FirstInterceptor implements Interceptor {
public void intercept(ActionInvocation invocation) {
System.out.println("1");
invocation.invoke();
System.out.println("-1");
}
}
public class SceondInterceptor implements Interceptor {
public void intercept(ActionInvocation invocation) {
// TODO Auto-generated method stub
System.out.println("2");
invocation.invoke();
System.out.println("-2");
}
}
4.接下来模拟将这两个拦截器注册到xml文件中,写ActionInvocation类
import java.util.ArrayList;
import java.util.List;
public class ActionInvocation {
Action a = new Action();
static int index=-1;
static List<Interceptor> list=new ArrayList<Interceptor>();
public ActionInvocation() {
this.list.add(new FirstInterceptor());
this.list .add(new SceondInterceptor());
}
public void invoke() {
index++;
if(index<list.size()) {
list.get(index).intercept(this);
}else {
a.execute();
}
}
}
5.最后写测试类
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
new ActionInvocation().invoke();
}
}
运行截图:
要为action配置拦截器,须在struts.xml中使用interceptor元素定义拦截器,在action标签中使用<interceptor-ref>指定引用的拦截器
<interceptor name="拦截器名" class="拦截器的完整类名"/>定义
<interceptor name="拦截器名"/>引用
如果有多个拦截器需要配置,那么可以使用拦截器栈来实现
<interceptors>
<interceptor name="name1" class="classname1"></interceptor>
<interceptor name="name2" class="classname2"></interceptor>
<interceptor-stack name="stackname">
<interceptor-ref name="name1"></interceptor-ref>
<interceptor-ref name="name2"></interceptor-ref>
</interceptor-stack>
</interceptors>
然后在action中引用
拦截器暂且就总结这些,如有新的认识会更新。
如有错误之处,欢迎指正。
附一张Struts2的工作流程时序图: