struts2 拦截器
拦截器
2.自定义拦截器
  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>
  
 
                    
                     
                    
                 
                    
                 
 
         
                
            
         浙公网安备 33010602011771号
浙公网安备 33010602011771号