一、攔截器的實現(xiàn)

     實現(xiàn)一個攔截器非常簡單。實際上,一個攔截器就是一個普通的類,只是這個類必須實現(xiàn)com.opensymphony.xwork2.interceptor.Interceptor接口。Interceptor接口有如下三個方法:


public interface Interceptor extends Serializable 
{
    
void destroy();
    
void init();
    String intercept(ActionInvocation invocation
throws Exception;
}


 

其中initdestroy方法只在攔截器加載和釋放(都由Struts2自身處理)時執(zhí)行一次。而intercept方法在每次訪問動作時都會被調用。Struts2在調用攔截器時,每個攔截器類只有一個對象實例,而所有引用這個攔截器的動作都共享這一個攔截器類的對象實例,因此,在實現(xiàn)Interceptor接口的類中如果使用類變量,要注意同步問題。

下面我們來實現(xiàn)一個簡單的攔截器,這個攔截器通過請求參數(shù)action指定一個攔截器類中的方法,并調用這個方法(我們可以使用這個攔截器對某一特定的動作進行預處理)。如果方法不存在,或是action參數(shù)不存在,則繼續(xù)執(zhí)行下面的代碼。如下面的URL

http://localhost:8080/struts2/test/interceptor.action?action=test

訪問上面的url后,攔截器會就會調用攔截器中的test方法,如果這個方法不存在,則調用invocation.invoke方法,invoke方法和Servlet過濾器中調用FilterChain.doFilter方法類似,如果在當前攔截器后面還有其他的攔截器,則invoke方法就是調用后面攔截器的intercept方法,否則,invoke會調用Action類的execute方法(或其他的執(zhí)行方法)。

下面我們先來實現(xiàn)一個攔截器的父類ActionInterceptor。這個類主要實現(xiàn)了根據(jù)action參數(shù)值來調用方法的功能,代碼如下:


 

package interceptor;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;
import javax.servlet.http.*;
import org.apache.struts2.*;

public class ActionInterceptor implements Interceptor
{
    
protected final String INVOKE = "##invoke";
   
    
public void destroy()
    {
        System.out.println(
"destroy");
    }

    
public void init()
    {
        System.out.println(
"init");
    }

    
public String intercept(ActionInvocation invocationthrows Exception
    {    
        HttpServletRequest request 
= ServletActionContext.getRequest();
        String action 
= request.getParameter("action");
        System.out.println(
this.hashCode());
        
if (action != null)
        {
            
try
            {
                java.lang.reflect.Method method 
= this.getClass().getMethod(action);
                String result 
= (String)method.invoke(this);
                
if(result != null)
                {
                    
if(!result.equals(INVOKE))
                        
return result;
                }
                
else
                    
return null;
            }
            
catch (Exception e)
            {
            }
        }
        
return invocation.invoke();
    }
}


 

從上面代碼中的intercept方法可以看出,在調用action所指定的方法后,來判斷返回值。可能發(fā)生的情況有三種:

1.        返回值為null,執(zhí)行return null

2.        返回值為INVOKE,執(zhí)行return invockation.invoke()

3.        其他情況,執(zhí)行return result result表示指定方法的返回值,如上面代碼所示。

    在實現(xiàn)完上面的攔截器父類后,任何繼承于ActionInterceptor類的攔截器都可以自動根據(jù)action的參數(shù)值調用自身的相應方法。下面我們來實現(xiàn)一個擁有兩個動作方法testprint的攔截器類。代碼如下:


package interceptor;

import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;

public class MultiMethodInterceptor extends ActionInterceptor
{
    
public String test() throws Exception
    {
        HttpServletResponse response 
= ServletActionContext.getResponse();
        response.getWriter().println(
"invoke test");
        
return this.INVOKE;
    }

    
public String print() throws Exception
    {
        HttpServletResponse response 
= ServletActionContext.getResponse();
        response.getWriter().println(
"invoke print");

        
return null;
    }
}


 

test方法返回了INVOKE,因此,在執(zhí)行完這個方法后,Struts2會接著調用其他攔截器的intercept方法或Action類的execute方法。而print方法在執(zhí)行完后,只是返回了null,而不再調用其他的方法了,也就是訪問如下的url時,動作的execute方法將不會執(zhí)行:

    http://localhost:8080/struts2/test/ddd.action?action=print

    下面我們來實現(xiàn)一個Action類,代碼如下:

package action;

import org.apache.struts2.*;
import com.opensymphony.xwork2.ActionSupport;

public class InterceptorAction extends ActionSupport
{
    
public String abcd() throws Exception
    {
        ServletActionContext.getResponse().getWriter()
                .println(
"invoke abcd");
        
return null;
    }
}


 

在這個Action類中,只有一個abcd方法,實際上,這個方法相當于execute方法,在下面會設置動作的method屬性為abcd。下面我們來在struts.xml中定義攔截器類和動作,代碼如下:


 

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd"
>
<struts>
    
<package name="demo" extends="struts-default" namespace="/test">
        
<interceptors>
            
<interceptor name="method" class="interceptor.MultiMethodInterceptor" />
                
<interceptor-stack name="methodStack">
                    
<interceptor-ref name="method" />
                    
<interceptor-ref name="defaultStack" />
                
</interceptor-stack>
        
</interceptors>

        
<action name="interceptor" class="action.InterceptorAction" method="abcd">
            
<interceptor-ref name="methodStack" />
        
</action>
    
</package>
</struts>


 

在配置上面的methodStack攔截器時要注意,最好在后面引用defaultStack,否則很多通過攔截器提供的功能將失去。

OK,現(xiàn)在訪問如下的URL

    http://localhost:8080/struts2/test/ddd.action?action=test

在瀏覽器中將會出現(xiàn)如下的字符串:

    invoke test

invoke abcd

而如果訪問http://localhost:8080/struts2/test/ddd.action?action=print,將會只出現(xiàn)如下的字符串:

    invoke print

大家可以看出,訪問這個url時并沒有調用abcd方法。如果隨便指定的action值的話,則只調用abcd方法,如訪問http://localhost:8080/struts2/test/ddd.action?action=aaa,就只會輸出invoke abcd


二、攔截器的參數(shù)

   
我們在使用很多Struts2內置的攔截器時會發(fā)現(xiàn)有很多攔截器都帶參數(shù),當然。我們自己做的攔截器也可以加上同樣的參數(shù)。有兩個參數(shù)比較常用,這兩個參數(shù)是includeMethodsexcludeMethods,其中includeMethods指定了攔截器要調用的Action類的執(zhí)行方法(默認是execute),也就是說,只有在includeMethods中指定的方法才會被Struts2調用,而excludeMethods恰恰相反,在這個參數(shù)中指定的執(zhí)行方法不會被Struts2調用。如果有多個方法,中間用逗號(,)分隔。在Struts2中提供了一個抽象類來處理這兩個參數(shù)。這個類如下:

com.opensymphony.xwork2.interceptor.MethodFilterInterceptor

   
如有繼承于這個類的攔截器類都會自動處理includeMethodsexcludeMethods參數(shù),如下面的攔截器類所示:

package interceptor;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.*;

public class MyFilterInterceptor extends MethodFilterInterceptor
{
    
private String name;
    
public String getName()
    {
        
return name;
    }
    
public void setName(String name)
    {
        
this.name = name;
    }
    @Override
    
protected String doIntercept(ActionInvocation invocationthrows Exception
    {
        System.out.println(
"doIntercept");
        System.out.println(name);
        
return invocation.invoke();
    }
}


    MethodFilterInterceptor的子類需要實現(xiàn)doIntercept方法(相當于Interceptorintercept方法),如上面代碼所示。在上面的代碼中還有一個name屬性,是為了讀取攔截器的name屬性而設置的,如下面的配置代碼所示:


<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd"
>
<struts>
    
<package name="demo" extends="struts-default" namespace="/test">
        
<interceptors>
            
<interceptor name="method" class="interceptor.MultiMethodInterceptor" />
                
<interceptor name="filter"
                    class
="interceptor.MyFilterInterceptor">
                    
<param name="includeMethods">abcd</param>
                    
<param name="name">中國</param>
                
</interceptor>
                
<interceptor-stack name="methodStack">
                    
<interceptor-ref name="method" />
                    
<interceptor-ref name="filter" />
                    
<interceptor-ref name="defaultStack" />
                
</interceptor-stack>
        
</interceptors>

        
<action name="interceptor" class="action.InterceptorAction" method="abcd">
            
<interceptor-ref name="methodStack" />
        
</action>
    
</package>
</struts>


    再次訪問http://localhost:8080/struts2/test/ddd.action?action=test, Struts2就會調用MyFilterInterceptordoIntercept方法來輸出name屬性值。如果將上面的includeMethods參數(shù)值中的abcd去掉,則Action類的abcd方法不會被執(zhí)行。