Struts2——拦截器

实现拦截器

自定义拦截器需要实现Interceptor接口:

public class MyInterceptor implements Interceptor{
    //销毁该拦截器之前的回调方法
    void destory(){
        //...
    };
    //初始化该拦截器的回调方法
    void init(){
        //...
    };
    //拦截器实现拦截的逻辑方法
    String intercept(ActionInvocation invocation)throws Exception{
        //得到当前被拦截的Action
        XXXAction action = (XXXAction)invocation.getAction();
        //如果需要对上下文进行处理
        ActionContext ctx = invocation.getIncocationContext();
        ...
        //调用
        String result = invocation.invoke();//可以看出拦截器的本质其实就是AOP
        return result;
    }
}

上面的拦截器是针对整个Action类的拦截器,如果我们需要拦截方法,那我们需要继承MethodFilterInterceptor:

public class MyMethodInterceptor extends MethodFilterInterceptor{
    //通过重写doInterceptor实现对Action的拦截处理
    public String doInterceptor(ActionInvocation invocation){
        //该方法的实现逻辑同上一种对类进行拦截的Action
    }
}

方法拦截器的实现和类级别的拦截器的实现上大同小异,其区别主要是配置上的区别:

<interceptor-ref name="myMethodInterceptor">
    <param name="excludeMethods">XXX,XXX</param>
    <param name="includeMethods">XXX,XXX</param>
    <!--两者冲突以includeMethods为准-->
</interceptor-ref>

配置拦截器

单独配置的拦截器:

<interceptor name="拦截器名" class="拦截器实现类">
    <param name="参数名">参数值</param>
</interceptor>

配置拦截器栈:

<interceptor-stack name="拦截器栈名">
    <interceptor-ref name="拦截器名">
    <!--其他的拦截器同上配置-->
    <!--拦截器栈中还可以包含拦截器栈的引用-->
    <interceptor-ref name="拦截器栈名">
</interceptor>

配置好之后,拦截器的使用:

<action>
    <result ...></result>
    <interceptor-ref name="拦截器名">
</action>

上面的拦截器是Action范围内的拦截器,我们还可以配置包默认的拦截器:

<package>
    <interceptors>
        //拦截器配置
    </interceptors>
    <default-interceptor-ref name="拦截器名"/>
    <action../>
</package>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值