码迷,mamicode.com
首页 > 其他好文 > 详细

struts2自定义拦截器

时间:2017-02-21 17:59:56      阅读:183      评论:0      收藏:0      [点我收藏+]

标签:bst   ext   节点   namespace   cat   rate   介绍   control   action   

自定义拦截器

  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>

struts2自定义拦截器

标签:bst   ext   节点   namespace   cat   rate   介绍   control   action   

原文地址:http://www.cnblogs.com/FriendlyMaKe/p/6424701.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!