天天看點

轉載:Struts2攔截器之攔截器的方法過濾

轉自:http://enetq.blog.51cto.com/479739/542619

在Action中使用攔截器,預設情況下回攔截Action中所有的方法,但是在某些情況下,可能隻需要攔截Action中的一個或多個方法,有時候也希望不攔截某個方法,這個在Struts2中是怎麼實作的呢 ?

攔截器方法過濾:讓攔截器有選擇的攔截Action中的某個方法!

Struts2中提供了一個MethodFilterInterceptor類,開發者自定義的攔截器隻需要繼承該類就可以使用這個方法過濾的功能,來攔截Action中特定的方法!

檢視API文檔 可以看到這個類為:

/*  

 * Copyright 2002-2006,2009 The Apache Software Foundation.  

 *   

 * Licensed under the Apache License, Version 2.0 (the "License");  

 * you may not use this file except in compliance with the License.  

 * You may obtain a copy of the License at  

 *      http://www.apache.org/licenses/LICENSE-2.0  

 * Unless required by applicable law or agreed to in writing, software  

 * distributed under the License is distributed on an "AS IS" BASIS,  

 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  

 * See the License for the specific language governing permissions and  

 * limitations under the License.  

 */ 

package com.opensymphony.xwork2.interceptor;  

import com.opensymphony.xwork2.ActionInvocation;  

import com.opensymphony.xwork2.util.TextParseUtil;  

import com.opensymphony.xwork2.util.logging.Logger;  

import com.opensymphony.xwork2.util.logging.LoggerFactory;  

import java.util.Collections;  

import java.util.Set;  

/**  

 * <!-- START SNIPPET: javadoc -->  

 * MethodFilterInterceptor is an abstract <code>Interceptor</code> used as  

 * a base class for interceptors that will filter execution based on method   

 * names according to specified included/excluded method lists.  

 * <p/>  

 * Settable parameters are as follows:  

 * <ul>  

 *      <li>excludeMethods - method names to be excluded from interceptor processing</li>  

 *      <li>includeMethods - method names to be included in interceptor processing</li>  

 * </ul>  

 * <b>NOTE:</b> If method name are available in both includeMethods and   

 * excludeMethods, it will be considered as an included method:   

 * includeMethods takes precedence over excludeMethods.  

 * Interceptors that extends this capability include:  

 *    <li>TokenInterceptor</li>  

 *    <li>TokenSessionStoreInterceptor</li>  

 *    <li>DefaultWorkflowInterceptor</li>  

 *    <li>ValidationInterceptor</li>  

 * <!-- END SNIPPET: javadoc -->  

 * @author <a href='mailto:the_mindstorm[at]evolva[dot]ro'>Alexandru Popescu</a>  

 * @author Rainer Hermanns  

 * @see org.apache.struts2.interceptor.TokenInterceptor  

 * @see org.apache.struts2.interceptor.TokenSessionStoreInterceptor  

 * @see com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor  

 * @see com.opensymphony.xwork2.validator.ValidationInterceptor  

 * @version $Date: 2009-12-27 19:18:29 +0100 (Sun, 27 Dec 2009) $ $Id: MethodFilterInterceptor.java 894090 2009-12-27 18:18:29Z martinc $  

public abstract class MethodFilterInterceptor extends AbstractInterceptor {  

    protected transient Logger log = LoggerFactory.getLogger(getClass());  

    protected Set<String> excludeMethods = Collections.emptySet();  

    protected Set<String> includeMethods = Collections.emptySet();  

    public void setExcludeMethods(String excludeMethods) {  

        this.excludeMethods = TextParseUtil.commaDelimitedStringToSet(excludeMethods);  

    }  

    public Set<String> getExcludeMethodsSet() {  

        return excludeMethods;  

    public void setIncludeMethods(String includeMethods) {  

        this.includeMethods = TextParseUtil.commaDelimitedStringToSet(includeMethods);  

    public Set<String> getIncludeMethodsSet() {  

        return includeMethods;  

    @Override 

    public String intercept(ActionInvocation invocation) throws Exception {  

        if (applyInterceptor(invocation)) {  

            return doIntercept(invocation);  

        }   

        return invocation.invoke();  

    protected boolean applyInterceptor(ActionInvocation invocation) {  

        String method = invocation.getProxy().getMethod();  

        // ValidationInterceptor  

        boolean applyMethod = MethodFilterInterceptorUtil.applyMethod(excludeMethods, includeMethods, method);  

        if (log.isDebugEnabled()) {  

            if (!applyMethod) {  

                log.debug("Skipping Interceptor... Method [" + method + "] found in exclude list.");  

            }  

        }  

        return applyMethod;  

    /**  

     * Subclasses must override to implement the interceptor logic.  

     *   

     * @param invocation the action invocation  

     * @return the result of invocation  

     * @throws Exception  

     */ 

    protected abstract String doIntercept(ActionInvocation invocation) throws Exception;  

}  

是AbstractInterceptor攔截器的子類,實作了Interceptor和Serializable接口

MethodFilerInterceptor實作方法過濾中用到的兩個參數

execludeMethods:該參數指定攔截器拒絕攔截的方法清單,多個方法用“,”隔開,指定了這個參數,攔截器不會攔截指定清單中的方法,就是所謂的黑名單

includeMethods:該參數指定攔截器需要攔截的方法清單,如果指定了參數,則指定的Action在執行前會被攔截,即白名單。

主要方法:

①protected abstract String doIntercept(ActionInvocation invocation) throws Exception;  必須重寫此方法,實作攔截。

②String interceptor(ActionInvocation invocation):繼承自AbstractInterceptor類,方法不需要強制重寫

③void setExcludeMethods(String excludeMethods):設定攔截器黑名單,參數為Action一方法名。攔截器不攔截該方法

④void setIncludeMethods(String includeMethods):設定攔截器白名單,參數為Action一方法名。攔截器會攔截該方法

⑤Set<String> getExcludeMethodsSet():獲得攔截器的黑名單

⑥Set<String> getIncludeMethodsSet():獲得攔截器的白名單

一般開發者隻需要重寫doIntercept方法即可!下面給出一個執行個體:

一。實作方法過濾的攔截器實作類:FilterInterceptor.java繼承自MethodFilterInterceptor類

package com.yaxing.interceptor;  

import java.util.Date;  

import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor;  

public class FilterInterceptor extends MethodFilterInterceptor {  

    private String name;  

    public String getName() {  

        return name;  

    public void setName(String name) {  

        this.name = name;  

    protected String doIntercept(ActionInvocation invocation) throws Exception {  

        // TODO Auto-generated method stub  

        FilterAction fa= (FilterAction)invocation.getAction();  

        System.out.println(name+"攔截器在Action執行前攔截"+new Date());  

        String result=invocation.invoke();  

        System.out.println(name+"攔截器在Action執行後攔截"+new Date());  

        return result;  

在該類中name屬性用來辨別攔截器的名稱,友善控制台的輸出

二。Action:業務控制器FilterAction.java

import com.opensymphony.xwork2.ActionSupport;  

public class FilterAction extends ActionSupport {  

    private String msg;  

    public String getMsg() {  

        return msg;  

    public void setMsg(String msg) {  

        this.msg = msg;  

    public String method1() throws Exception {  

        System.out.println("Action執行方法:method1()");  

        return SUCCESS;  

    public String method2() throws Exception {  

        System.out.println("Action執行方法:method2()");  

    public String method3() throws Exception {  

        System.out.println("Action執行方法:method3()");  

三。配置檔案struts.xml

<?xml version="1.0" encoding="UTF-8" ?> 

<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd"> 

<struts> 

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

    <interceptors> 

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

        <interceptor name="Myinterceptor" class="com.yaxing.interceptor.Myinterceptor"></interceptor> 

        <interceptor name="SimpleInterceptor" class="com.yaxing.interceptor.SimpleInterceptor"></interceptor> 

        <interceptor name="FilterInterceptor" class="com.yaxing.interceptor.FilterInterceptor"></interceptor> 

    </interceptors> 

    <action  name="Reg" class="com.yaxing.interceptor.Reg" method="execute"> 

           <result name="success">/Success.jsp</result> 

           <result name="input">/Reg.jsp</result> 

           <interceptor-ref name="defaultStack"></interceptor-ref> 

           <interceptor-ref name="SimpleInterceptor"></interceptor-ref> 

    </action> 

    <action name="FilterAction" class="com.yaxing.interceptor.FilterAction"> 

            <result name="success">/MethodFilter.jsp</result> 

<!--使用攔截器-->

            <interceptor-ref name="defaultStack"></interceptor-ref> 

            <interceptor-ref name="FilterInterceptor"> 

<!--攔截器黑白名單-->

                 <param name="includeMethods">method1</param> 

                 <param name="excludeMethods">method2</param> 

<!--指定參數name的值-->

<param name="name">FilterMethod</param>

            </interceptor-ref> 

</package> 

</struts>      

四。jsp視圖 MethodFilter.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 

<%@ taglib prefix="s" uri="/struts-tags" %> 

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 

<html> 

  <head> 

    <title>My JSP 'MethodFilter.jsp' starting page</title> 

    <meta http-equiv="pragma" content="no-cache"> 

    <meta http-equiv="cache-control" content="no-cache"> 

    <meta http-equiv="expires" content="0">      

    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> 

    <meta http-equiv="description" content="This is my page"> 

    <!--  

    <link rel="stylesheet" type="text/css" href="styles.css">  

    --> 

  </head> 

  <body> 

    <s:form id="id" action="FilterAction!method1.action"> 

       <s:textfield name="msg" label="請輸入資訊:"/> 

       <s:submit value="送出"/> 

    </s:form> 

  </body> 

</html> 

五:運作結果:

轉載:Struts2攔截器之攔截器的方法過濾

可以看出method1方法攔截了。而method2方法是放到了黑名單中。

②将JSP視圖中action 換成FilterAction!method2.action 輸出資訊

轉載:Struts2攔截器之攔截器的方法過濾

因為指定method2為黑名單,不會攔截,是以是沒有攔截資訊的。

轉載:Struts2攔截器之攔截器的方法過濾

可以看到,雖然沒有在黑名單中指定method3,因為配置檔案顯示指定了白名單,是以攔截器隻攔截白名單中指定的方法!