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;
imp
imp
imp
imp
imp
imp
/**
* 攔截器需要繼承AbstractInterceptor,或者是實現Interceptor接口(AbstractInterceptor也是實現的Interceptor)
*/
@SuppressWarnings("serial")
public class AuthorInterceptor extends AbstractInterceptor {
/*不清楚為什么,在攔截器中注入業務層或者數據訪問層的對象始終為null,
但是注入act
轉去調用業務層的方法..*/
private YongHuAction yonghuAction;
//getter and setter...
@SuppressWarnings("unchecked")
public String intercept(ActionInvocation invocation) throws Exception {
System.out.println("=======檢查act
// 獲得攔截到的act
String actionName =invocation.getInvocationContext().getName();
ActionContext ctx = invocation.getInvocationContext();
Map session = ctx.getSession();
//如果攔截到的act
if (actionName.equals("logins")) {
return invocation.invoke();
} else {
//session中取得當前用戶.
SysYonghu yonghu = (SysYonghu) session.get("current_user");
//如果當前用戶為空,轉到登錄頁面.
if(yonghu==null){
session.put("tip", "請登錄...");
return Act
}
//調用act
boolean result=yonghuAction.isHave(actionName, yonghu);
if(result){
return invocation.invoke();
}else{
session.put("quanxian_tip", "您沒有該資源的權限!");
return Act
}
}
}
}
3. 在使用的時候,如果有多個struts配置文件,只需要繼承”sys”即可.如果其他配置文件中又定義了攔截器.那么這個攔截器將失效.
不足之處:攔截器只能攔截訪問的act