struts2自定义拦截器

自定义拦截器

  1>.添加一个类,让它继承AbstractInterceptor类,或者实现Interceptor接口

     public class TimeInterceptor extends AbstractInterceptor {

    /**
     * 拦截器的核心方法intercept的返回值是一个字符串
     */
    @Override
    public String intercept(ActionInvocation invocation) throws Exception {
        // TODO Auto-generated method stub
        return "login";
    }

     }

  2>.在struts.xml的package中添加interceptors子节点,并在它下面添加Interceptor节点

     <package name="goods" namespace="/goods" extends="common-pkg">
    
        <interceptors>
            <interceptor name="timeInterceptor" class="com.wskj.struts2.interceptor.TimeInterceptor"></interceptor>
        </interceptors>

     </package>

  3>.在想被拦截的action节点下添加子节点interceptor-ref

     <action name="list_Category" class="com.wskj.struts2.controller.CategoryAction" method="list">
        
    <interceptor-ref name="timeInterceptor"></interceptor-ref>
        
    <result name="list" type="dispatcher">/pages/Category/list.jsp</result>
     </action>

3.配置默认的拦截器

  <!-- 设置默认的拦截器 -->
  <default-interceptor-ref name="timeInterceptor"></default-interceptor-ref>

  注意:设置默认的拦截器之后,该拦截器将对该package中所有的action起作用。

4.defaultStack介绍

  struts2提供了一个默认的拦截器:defaultStack。

  defaultStack是一个拦截器栈。拦截器栈就是多个拦截器的组合。

  在自定义拦截器之后,struts2提供的默认的拦截器将不再起作用。所以在自定义拦截器后,还会将默认的拦截器栈加入到当前的拦截器栈中。

  自定义拦截器栈

      <interceptors>
    <interceptor name="timeInterceptor" class="com.wskj.struts2.interceptor.TimeInterceptor"></interceptor>
            
    <!-- 定义拦截器栈 -->
    <interceptor-stack name="goodsStack">
        <interceptor-ref name="timeInterceptor"></interceptor-ref>
        <interceptor-ref name="defaultStack"></interceptor-ref>
    </interceptor-stack>
            
      </interceptors>

      <!-- 设置默认的拦截器 -->
      <default-interceptor-ref name="goodsStack"></default-interceptor-ref>

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值