常用的struts2的Interceptor攔截器

 iLife's 博客http://blog.csdn.net/fei1502816 

 

我們可以自定義Interceptor繼承com.opensymphony.xwork2.interceptor.AbstractInterceptor,即可定義攔截器:
    攔截器可以與Filter過濾器集合起來使用,Interceptor的配置在struts.xml中配置,可以攔截指定的struts2請求,一般是指.action後綴的請求。

package edu.press.utils;

import javax.servlet.http.*;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import org.apache.struts2.ServletActionContext;

/**
* Interceptors for security
* @author
* @version 1.0
* 
*/
public class AdminInterceptor extends AbstractInterceptor {

    private static final long serialVersionUID = 1L;
    private HttpSession session;

    public String intercept(ActionInvocation invocation) throws Exception {
        session = ServletActionContext.getRequest().getSession(true);
        // 簡單的驗證會話session是否有指定屬性
        if (session.getAttribute("XXXXXXXX") != null) {
            return invocation.invoke(); //權限符合,請求順利執行
        }
        return Action.LOGIN; //請求未通過,轉向LOGIN的result
    }
}

在struts.xml文件中配置:

<package name="press" extends="struts-default">
        <interceptors>
            <interceptor name="adminInterceptor"
                />
            <interceptor-stack name="adminStack">
                <interceptor-ref name="basicStack" />
                <interceptor-ref name="adminInterceptor" />
            </interceptor-stack>
        </interceptors>
        <global-results>
              <result name="login" type="redirect">/login.jsp?err=1</result>
        </global-results>
下邊這是我們項目中的定義,攔截了多有繼承struts-defult的package裏的Action
<package name="struts-estone" extends="struts-default"> 
     <interceptors>
            <interceptor name="authority" class="com.estone.www.kepuoa.admin.action.interceptor.AuthorityInterceptor"/>
            <interceptor-stack name="auctionStack">
                <interceptor-ref name="defaultStack"/>
                <interceptor-ref name="authority"/>
            </interceptor-stack>
  </interceptors>
        <default-interceptor-ref name="auctionStack"/>
  <global-results>
   <!-- 下面定義的結果對所有的Action都有效 -->
   <result name="login" type="redirect">/forword.jsp</result>
   <result name="input">/error.jsp</result>
  </global-results>
  <global-exception-mappings>
   <exception-mapping result="input" exception="java.lang.Exception"></exception-mapping>
  </global-exception-mappings>
 </package> 
 
對於需要攔截的action,可按照如下例子:
<action name="uploadResource" method="upload">
            <interceptor-ref name="adminStack"/>
            <result name="success" type="redirect">XXXXXXXXXXX</result>
            <result name="input">XXXXXXXXXXXXXXXX</result>
 </action>
發佈了30 篇原創文章 · 獲贊 16 · 訪問量 37萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章