Struts2---->interceptor

一、什么是拦截器

Interceptor是Struts 2的一个强有力的工具,有许多功能(feature)都是构建于它之上,如国际化转换器校验等。

拦截器,在AOP(Aspect-Oriented Programming)中用于在某个方法或字段被访问之前,进行拦截然后在之前或之后加入某些操作。拦截是AOP的一种实现策略。

在Webwork的中文文档的解释为——拦截器是动态拦截Action调用的对象。它提供了一种机制可以使开发者可以定义在一个action执行的前后执行的代码,也可以在一个action执行前阻止其执行。同时也是提供了一种可以提取action中可重用的部分的方式。

拦截器链(Interceptor Chain,在Struts 2中称为拦截器栈Interceptor Stack)。拦截器链就是将拦截器按一定的顺序联结成一条链。在访问被拦截的方法或字段时,拦截器链中的拦截器就会按其之前定义的顺序被调用。

实现原理

Struts 2的拦截器实现相对简单。当请求到达Struts 2的ServletDispatcher时,Struts 2会查找配置文件,并根据其配置实例化相对的拦截器对象,然后串成一个列表(list),最后一个一个地调用列表中的拦截器,如图所示。

二、interceptor模拟

Action.java

public class Action {
	public void execute() {
		System.out.println("execute!");
	}
}

ActionInvocation.java

import java.util.ArrayList;
import java.util.List;


public class ActionInvocation {
	List<Interceptor> interceptors = new ArrayList<Interceptor>();
	int index = -1;
	Action a = new Action();
	
	public ActionInvocation() {
		this.interceptors.add(new FirstInterceptor());
		this.interceptors.add(new SecondInterceptor());
		
	}
	
	public void invoke() {
		index ++;
		if(index >= this.interceptors.size()) {
			a.execute();
		}else {
			
			this.interceptors.get(index).intercept(this);
		}
	}
}

Interceptor.java 接口

public interface Interceptor {
	public void intercept(ActionInvocation invocation) ;
}

FirstInterceptor.java

public class FirstInterceptor implements Interceptor {

	public void intercept(ActionInvocation invocation) {
		System.out.println(1);
		invocation.invoke();
		System.out.println(-1);
	}

}

SecondInterceptor.java

public class SecondInterceptor implements Interceptor {

	public void intercept(ActionInvocation invocation) {
		System.out.println(2);
		invocation.invoke();
		System.out.println(-2);
	}

}

Main.java

public class Main {
	public static void main(String[] args) {
		new ActionInvocation().invoke();
	}
}

 

文章:http://www.blogjava.net/max/archive/2006/12/06/85925.html

 

posted on 2012-09-03 10:22  小强斋太  阅读(247)  评论(0编辑  收藏  举报

导航