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


      我们来进行一下拦截器的原理分析,从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的。

    过程可以看图。




  • 相关阅读:
    xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools), missing xcrun
    查看公钥
    Flutter 环境配置,创建工程
    Flutter 简介
    Mac版本 FinalShell SSH工具
    windows下如何生成公钥和私钥
    pyqt 打包为dmg文件
    apple 升级后shell切换为zsh
    dart 类共享变量
    python 获取一小时前的时间戳
  • 原文地址:https://www.cnblogs.com/riskyer/p/3313114.html
Copyright © 2020-2023  润新知