Struts2拦截器原理简介

最近再学struts2。书中讲到struts2的拦截器实现原理,看得一头雾水。几个方法之间循环调用,有点头晕。所以我写了个简化版的程序,理清原理。

Action类,相当于struts2中的action。execute()方法。

public class Action {
    public String execute(){
        System.out.println("action execute()");
        return "success";
    }
}
Interceptor接口(拦截器)。 
public interface Interceptor {
    String intercept(Invocation invocation);
}
 
Interceptor的三个实现类:
public class InterceptorA implements Interceptor {
    @Override
    public String intercept(Invocation invocation) {
        System.out.println("A before action");
        String result=invocation.invoke();
        System.out.println("A after action");
        return result;
    }
}
public class InterceptorB implements Interceptor {
    @Override
    public String intercept(Invocation invocation) {
        System.out.println("B before action");
        String result=invocation.invoke();
        System.out.println("B after action");
        return result;
    }
}
public class InterceptorC implements Interceptor {
    @Override
    public String intercept(Invocation invocation) {
        System.out.println("C execute and return");
        return "failed";
    }
}

Invocation类,相当于ActionInvocation
public class Invocation {
    private List<Interceptor> interceptors=new ArrayList<>();
    private Action action=new Action();
    private Iterator<Interceptor> iter;
    {
        interceptors.add(new InterceptorA());
        interceptors.add(new InterceptorB());
//        interceptors.add(new InterceptorC());
        iter=interceptors.iterator();
    }
    public String invoke(){
        while(iter.hasNext()){
            Interceptor interceptor=iter.next();
            return interceptor.intercept(this);
        }
        return action.execute();
    }
}
运行结果:
A before action
B before action
action execute()
B after action
A after action
success
 
如果把注释去掉,运行结果:
A before action
B before action
C execute and return
B after action
A after action
failed

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值