Struts2攔截器簡單示例

一、定義攔截器

Struts2規定用戶自定義攔截器必須實現com.opensymphony.xwork2.interceptor.Interceptor接口

其中,init和destroy方法會在程序開始和結束時各執行一遍,不管使用了該攔截器與否,只要在struts.xml中聲明瞭該攔截器就會被執行。
intercept方法就是攔截的主體了,每次攔截器生效時都會執行其中的邏輯。

不過,struts中又提供了幾個抽象類來簡化這一步驟。
public abstract class AbstractInterceptor implements Interceptor;
public abstract class MethodFilterInterceptor extends AbstractInterceptor;
都是模板方法實現的。
其中AbstractInterceptor提供了init()和destroy()的空實現,使用時只需要覆蓋intercept()方法;
MethodFilterInterceptor則提供了includeMethods和excludeMethods兩個屬性,用來過濾執行該過濾器的action的方法。可以通過param來加入或者排除需要過濾的方法。

一般來說,攔截器的寫法都差不多。看下面的示例:

 

  1. /** 
  2.  * 自定義攔截器 
  3.  * 功能:若用戶已登錄繼續執行當前action, 
  4.  *      否則返回登錄頁面 
  5.  * @author zhezi 
  6.  * 
  7.  */ 
  8. @SuppressWarnings("serial"
  9. public class AuthInterceptor extends AbstractInterceptor { 
  10.      
  11.      
  12.     @Override 
  13.     public String intercept(ActionInvocation invocation) throws Exception { 
  14.         HttpServletRequest request = ServletActionContext.getRequest(); 
  15.         HttpSession session = request.getSession(); 
  16.         if(session.getAttribute(Const.user) == null){ 
  17.             return Action.LOGIN; 
  18.         } 
  19.         String result = invocation.invoke(); 
  20.         return result; 
  21.     } 

二、聲明攔截器

在struts中攔截器實際上分爲攔截器和攔截器棧,攔截器棧可以包含一到多個攔截器或者攔截器棧。需將自定義攔截器加上struts缺省攔截器形成新的缺省攔截器。

特別::需注意攔截器順序,默認攔截器在上。


  1. <interceptors>  
  2.         <interceptor name="login" class="jp.struts.interceptor.AuthInterceptor"></interceptor>  
  3.         <interceptor-stack name="myDefault">  
  4.             <!-- 引用默認攔截器 -->   
  5.             <interceptor-ref name="defaultStack"></interceptor-ref>  
  6.             <!-- 引用自定義攔截器 -->   
  7.             <interceptor-ref name="login"></interceptor-ref> 
  8. <interceptor-ref name="myInterceptor3">               
  9.   <!--不攔截的方法-->                 
  10. <param name="excludeMethods">test,execute</param>                 <!--包含攔截的方法-->                 
  11. <param name="includeMethods">test</param>             
  12. </interceptor-ref>
  13.         </interceptor-stack>  
  14.     </interceptors>  
  15.     <default-interceptor-ref name="myDefault"></default-interceptor-ref>  

三、定義全局result

因爲全局定義了攔截器,雖然攔截器在通過攔截的情況下會返回特定Action的result,但有時候比如權限驗證失敗等情況下,自定義攔截器會返回自定義的結果,不屬於任何特定Action,所以我們也需要定義一個全局result用以響應這個攔截器的返回值。

 

  1. <global-results> 
  2.             <result name="Exception">/common/exception.jsp</result> 
  3.             <result name="RuntimeException">/common/runtime_exception.jsp</result> 
  4.             <result name="login" type="redirect">/login.jsp</result> 
  5.         </global-results> 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章