现在的位置: 首页 > 综合 > 正文

Struts2 学习笔记18 拦截器原理分析

2019年08月31日 ⁄ 综合 ⁄ 共 1410字 ⁄ 字号 评论关闭

  我们来进行一下拦截器的原理分析,从Struts2的源代码开始,然后我们手动创建一个项目进行模拟。(源代码需要下载然后添加好才能看到)我们可以用Debug来读源码。

  从doFilter开始执行,流程如图。

下面是Struts2官方的图。

这其中主要要解释的就是重复调用一个个interceptor(是从配置文件中读取的),当全部调用完成后,再调用Action。

下面我们用一个小项目来模拟一下,就很好理解了(项目中的类名和Struts2中的相同或类似)。

我们新建了一个Java Project。

代码如下。

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

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 >= interceptors.size()){
			a.execute();
		}
		else {
			
			this.interceptors.get(index).intercept(this);
		}
	}
}


public class FirstInterceptor implements Interceptor{

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

}


public class SecondInterceptor implements Interceptor{

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

}


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


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


结果如图。

我们可以从结果中看到,进入FirstInterceptor中被拦截,然后调用SecondInterceptor,然后调用Action,再返回SecondInterceptor中,再进入FirstInterceptor,这是方法的执行过程,在Struts2中是调用配置文件中的interceptor,而在我们这个项目中是手动add的。

过程可以看图。




抱歉!评论已关闭.