Struts2之方法拦截器

一、实现Interceptor接口

public interface Interceptor extends Serializable{  
     public void init();  
     public void destroy();  
     public String intercept(ActionInvocation invocation)();  
}  

二、AbstractInterceptor继承类

重写intercept()方法

invocation.invoke();表示该方法执行完后执行Action的execute()方法或者执行下一个拦截器  
invocation.getAction(); 可以将该法强制转换为Action的类类型  

三、MethodFilterInterceptor继承类
重写doIntercept()方法
MethodFilerInterceptor实现方法过滤中用到的两个参数:

  • execludeMethods
    该参数指定拦截器拒绝拦截的方法列表,多个方法用“,”隔开,指定了这个参数,拦截器不会拦截指定列表中的方法,就是所谓的黑名单
  • includeMethods
    该参数指定拦截器需要拦截的方法列表,如果指定了参数,则指定的Action在执行前会被拦截,即白名单。

MethodFilerInterceptor实现类:

public class UserInterceptor extends MethodFilterInterceptor{

    /**
     * 进行拦截的方法
     */
    protected String doIntercept(ActionInvocation invocation) throws Exception {
        // 获取session对象
        User user = (User) ServletActionContext.getRequest().getSession().getAttribute("existUser");
        if(user == null){
            // 说明,没有登录,后面就不会执行了
            return "login";
        }
        return invocation.invoke();
    }
}

struts.xml

<struts>

    <package name="hadwin" namespace="/" extends="struts-default">

        <!-- 配置拦截器 -->
        <interceptors>
            <interceptor name="UserInterceptor" class="com.hadwin.interceptor.UserInterceptor"/>
        </interceptors>

        <global-results>
            <result name="login">/login.htm</result>
        </global-results>

        <!-- 配置用户的模块 -->
        <action name="user_*" class="com.hadwin.action.UserAction" method="{1}">
            <!-- <result name="login">/login.htm</result> -->
            <result name="success">/index.htm</result>
            <interceptor-ref name="UserInterceptor">
                <!-- login方法不拦截,可以在这写也可以在interceptor定义处写都行 -->
                <param name="excludeMethods">login</param>
            </interceptor-ref>
            <interceptor-ref name="defaultStack"/>
        </action>

        <!-- 客户模块 -->
        <action name="customer_*" class="com.hadwin.action.CustomerAction" method="{1}">
            <interceptor-ref name="UserInterceptor"/>
            <interceptor-ref name="defaultStack"/>
        </action>

    </package>

</struts>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值