1.     首先要在struts的配置文件中進行攔截器的配置

    <package name="sys" extends="struts-default" namespace="/">

       <interceptors>

       <!-- 聲明自己的攔截器,起名叫check,對應的class屬性為自己編寫的攔截器路徑 -->

           <interceptor name="check" class="com.scm.actions.sys.AuthorInterceptor" />

           <!-- 定義攔截器棧,這里需要注意:在定制自己攔截器的同時,必須要把struts的默認棧加如里面,如果不加入,相當于把默認的覆蓋了,會出現異常! -->

           <interceptor-stack name="myCheck">

              <interceptor-ref name="check" />

              <interceptor-ref name="defaultStack" />

           </interceptor-stack>

       </interceptors>

 

 

       <!-- 定義默認攔截器 -->

       <default-interceptor-ref name="myCheck" />

      

       <!-- 定義全局結果,用于在攔截器中返回登錄頁面或者錯誤提示頁面 -->

       <global-results>

           <result name="login" type="redirect">/round.html</result>

           <result name="error">/scm_templates/Samples/index.html</result>

       </global-results>

    </package>

 

 

2.     編寫攔截器類

package com.scm.actions.sys;

 

import java.util.Map;

 

import com.opensymphony.xwork2.Action;

import com.opensymphony.xwork2.ActionContext;

import com.opensymphony.xwork2.ActionInvocation;

import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

import com.scm.domain.SysYonghu;

 

/**

 * 攔截器需要繼承AbstractInterceptor,或者是實現Interceptor接口(AbstractInterceptor也是實現的Interceptor)

 */

@SuppressWarnings("serial")

public class AuthorInterceptor extends AbstractInterceptor  {

 

    /*不清楚為什么,在攔截器中注入業務層或者數據訪問層的對象始終為null,

    但是注入action對象卻可以,所以這里我注入action對象,然后在action

    轉去調用業務層的方法..*/

    private YongHuAction yonghuAction;

    //getter and setter...

 

 

    @SuppressWarnings("unchecked")

    public String intercept(ActionInvocation invocation) throws Exception {

       System.out.println("=======檢查action=======");

 

       // 獲得攔截到的action名稱

       String actionName =invocation.getInvocationContext().getName();

       ActionContext ctx = invocation.getInvocationContext();

       Map session = ctx.getSession();

 

       //如果攔截到的action是請求登錄的action,則放行.

       if (actionName.equals("logins")) {

           return invocation.invoke();

       } else {

           //session中取得當前用戶.

           SysYonghu yonghu = (SysYonghu) session.get("current_user");

           //如果當前用戶為空,轉到登錄頁面.

           if(yonghu==null){

              session.put("tip", "請登錄...");

              return Action.LOGIN;

           }

//調用action中的方法, 判斷有無訪問此動作的權限

           boolean result=yonghuAction.isHave(actionName, yonghu);

           if(result){

              return invocation.invoke();

           }else{

              session.put("quanxian_tip", "您沒有該資源的權限!");

              return Action.ERROR;

           }

       }

    }

}

 

 3. 在使用的時候,如果有多個struts配置文件,只需要繼承”sys”即可.如果其他配置文件中又定義了攔截器.那么這個攔截器將失效.

 

 

 

 

不足之處:攔截器只能攔截訪問的action,如果直接訪問jsp或其他視圖,攔截器無法攔截. 所以應該配合filter使用;其實spring有自己的安全框架.可以把權限分的很細.希望有機會能用到.