2013-03-19 65 views
2

我定義了一個用於記錄時間的自定義攔截器,但它不起作用。 這裏是我的自定義攔截器代碼:爲什麼我的自定義攔截器不工作

public class TimeConsumedInterceptor extends AbstractInterceptor 
{ 

/* 
* {@inheritDoc} 
*/ 
@Override 
public String intercept(ActionInvocation invocation) throws Exception 
{ 
    long start = System.currentTimeMillis(); 
    String result = invocation.invoke(); 
    long end = System.currentTimeMillis(); 
    System.out.println("time consumed: " + (end - start)); 
    return result; 
} 

} 

我定義了一個新的XML文件:ECS-default.xml中(它是直屬src包)

<struts> 
<include file="struts-default.xml"></include> 
<!-- ecs-default package is abstract --> 
<package name="ecs-default" extends="struts-default" abstract="true"> 
    <interceptors> 
     <interceptor name="ecsTimer" class="com.nader.interceptor.TimeConsumedInterceptor"></interceptor> 

     <interceptor-stack name="ecsStack"> 
      <interceptor-ref name="ecsTimer"></interceptor-ref> 
      <interceptor-ref name="defaultStack"></interceptor-ref> 
     </interceptor-stack> 
    </interceptors> 
      <!-- default stack used for ecs-default package --> 
    <default-interceptor-ref name="ecsStack"></default-interceptor-ref> 

    <global-results> 
     <result name="error">error.jsp</result> 
    </global-results> 

    <global-exception-mappings> 
     <exception-mapping exception="java.lang.Exception" result="error" /> 
    </global-exception-mappings> 

</package> 
</struts> 

,並在struts.xml文件:

<struts> 
<include file="ecs-default.xml"></include> 
    <!-- define two empty package,/and /manager, extends ecs-default package --> 
<package name="default" namespace="/" extends="ecs-default"> 
</package> 

<package name="manager" namespace="/manager" extends="ecs-default"> 
</package> 

</struts> 

我調試代碼,在com.opensymphony.xwork2.DefaultActionInvocation類,List<InterceptorMapping> interceptorList = new ArrayList<InterceptorMapping>(proxy.getConfig().getInterceptors());proxy.getConfig().getInterceptors()返回defaultStack的18個攔截str中定義uts-default.xml,我的ecsTimer攔截器不在其中。所以爲什麼?我的配置有問題嗎?謝謝。

回答

2

正在爲每個動作執行創建DefaultActionInvocation。您只需執行您的自定義攔截器配置的操作即可在調試中看到它。

順便說一句,已經有timer攔截器,可以做你想做的。

+0

我使用Struts註釋,只是我照你說的,'@ParentPackage(值= 「JSON默認」) @Namespace(值= 「/經理」) @InterceptorRef(值= 「ecsStack」) 公衆class UserSearchAction擴展了ActionSupport' ...,現在它報告了一個錯誤:無法找到由ref-name ecsStack - [未知位置]引用的攔截器類。那麼如何解決呢?這個攔截器類肯定存在。 – hiway 2013-03-19 10:38:35

+0

我解決它,請參閱http://stackoverflow.com/questions/8600148/how-to-link-custom-interceptor-using-annotation。我認爲struts2註釋比xml配置更復雜。非常感謝。 – hiway 2013-03-19 11:10:12