Struts2 拦截器

一、拦截器简介

    拦截器是在访问Action之前/之后 进行拦截的,并且拦截器可插拔(添加/去除)的。
    优点:通用功能的封装,提供了可重用性。

二、预定义拦截器 和 拦截器栈
预定义拦截器 和 拦截器栈 在struts-default.xml中有定义
interceptor interceptor-stack

定义一个拦截器:

public class Myintercetor implements Interceptor{
    @Override
    public void destroy() {
        System.out.println("Myintercetor  destroy");}
    @Override
    public void init() {System.out.println("Myintercetor  init");   }
    @Override
    public String intercept(ActionInvocation invocation) throws Exception {
        System.out.println("Myintercetor  intercept,action执行之前");
        String result = invocation.invoke();//执行action
        //result为action的返回值
        System.out.println("Myintercetor  intercept,action执行之后");
        return result;
    }

注册与引用拦截器

<struts>
    <package name="helloworld" extends="struts-default">
    <!--定义拦截器  -->
        <interceptors>
            <interceptor name="Myintercetor" class="interceptor.Myintercetor"></interceptor>
        </interceptors>
        <action name="hello" class="action.hellowrod">
            <result name="success">helloword.jsp</result>
            <!--引用拦截器 ,访问按上下的顺序执行的 -->
            <interceptor-ref name="Myintercetor"></interceptor-ref>
            <interceptor-ref name="defaultStack"></interceptor-ref>
        </action>
    </package>
</struts>
  <!--定义拦截器  -->
        <interceptors>
            <interceptor name="Myintercetor" class="interceptor.Myintercetor"></interceptor>
            <interceptor name="Loginintercetor" class="interceptor.Loginintercetor"></interceptor>
    <!--定义拦截器栈  -->
            <interceptor-stack name="MyStack">
                        <interceptor-ref name="Loginintercetor"></interceptor-ref>
                         <interceptor-ref name="defaultStack"></interceptor-ref>
            </interceptor-stack>
        </interceptors>
   <!--设置默认拦截器栈,当有写名拦截器是不使用这个-->    
        <default-interceptor-ref name="MyStack"></default-interceptor-ref>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值