2011-09-15 101 views
2

我工作Struts2的攔截器。 我已閱讀,Struts2的攔截器就像過濾器,執行Action類之前,其執行和處理結果後一次(請糾正我,如果我錯了),那就是兩倍Struts2的:攔截正在只有一次,而不是兩次

但是,當我跑下面的代碼,攔截器只執行一次。 如果我犯了任何錯誤,請糾正我。 請參閱下面我的代碼:

這是我的struts.xml文件

<struts> 
<constant name="struts.devMode" value="true" /> 
    <package name="test" extends="struts-default"> 
<interceptors> 
<interceptor name="loginkiran" class="vaannila.MyLoginInterCeptor" /> 
</interceptors> 
     <action name="HelloWorld" class="vaannila.HelloWorld" method="kiran"> 
      <interceptor-ref name="loginkiran" /> 
      <result name="SUCCESS">/success.jsp</result> 
     </action> 
    </package> 
</struts> 

這是我的Action類

public class HelloWorld 
{ 
    public HelloWorld() { 
    } 
    public String kiran() { 
     System.out.println("iNSIDE THE aCTION CLASS"); 
     return "SUCCESS"; 
    } 
} 

這是我的攔截器類

public class MyLoginInterCeptor implements Interceptor { 

    @Override 
    public void destroy() { 
     // TODO Auto-generated method stub 
     System.out.println("Destroying Interceptor"); 

    } 

    @Override 
    public void init() { 

    } 

    @Override 
    public String intercept(ActionInvocation invocation) throws Exception { 

     HttpServletRequest request = (HttpServletRequest) ActionContext 
       .getContext().get(ServletActionContext.HTTP_REQUEST); 

     System.out.println("iNSIDE THE iNTERCEPTOR"); 

     return invocation.invoke(); 

    } 

} 

這是我的JSP文件:

<html> 
<body> 
<% 
System.out.println("iNSIde THE jsp"); 
%> 
</body> 
</html> 

對於上述代碼的輸出是這樣的:

iNSIDE THE iNTERCEPTOR 
iNSIDE THE aCTION CLASS 
iNSIde THE jsp 

回答

3

攔截器不執行兩次(也不是過濾器):攔截器(和過濾器)包裝動作(或servlet /等)

public String intercept(ActionInvocation invocation) throws Exception { 
    System.out.println("Before action invocation..."); 
    return invocation.invoke(); 
    System.out.println("After action invocation..."); 
} 
+0

感謝大衛,其實我follwed教程,其中指出,他們將執行兩次,請參閱該教程http://imageshack.us/photo/my-images/831/struts2.jpg/的這個形象,並請指正如果我誤解了 – Kiran

+1

我已經改正了你;圖像並沒有直接說明它們被執行了兩次 - 這是不明確的,並且不能準確地表示攔截的嵌套本質,也不表示攔截器在動作完成之前沒有執行完成。 (當然,除非正常流量中斷。) –