struts 2ソース分析

4030 ワード

以下のコードはStruts 2のinterceptor実装をシミュレートする
添付ファイルはstruts 2ソース分析です
1.インタフェースの定義
public interface Interceptor
{
    String intercept(ActionInvocation invocation) throws Exception;
}

2.インタフェース実装
public class InterceptorA implements Interceptor
{
    @Override
    public String intercept(ActionInvocation invocation) throws Exception
    {
	System.out.println("begin A");
	invocation.invoke();
	System.out.println("before interceptor's resultCode : " + invocation.getResultCode());
	System.out.println("end A");
	return "A";
    }

}
public class InterceptorB implements Interceptor
{
    @Override
    public String intercept(ActionInvocation invocation) throws Exception
    {
	System.out.println("begin B");
	invocation.invoke();
	System.out.println("before interceptor's resultCode : " + invocation.getResultCode());
	System.out.println("end B");
	return "B";
    }
}
public class InterceptorC implements Interceptor
{

    @Override
    public String intercept(ActionInvocation invocation) throws Exception
    {
	System.out.println("begin C");
	invocation.invoke();
	System.out.println("before interceptor's resultCode : " + invocation.getResultCode());
	System.out.println("end C");
	return "C";
    }
}

3.Invoke呼び出し

public class ActionInvocation
{

    Iterator<Interceptor> InterceptorIterator = null;
    private String resultCode = null;
    protected boolean executed = false;
    public String invoke()
    {

	if (executed)
	{
	    throw new IllegalStateException("Action has already executed");
	}
	if (InterceptorIterator.hasNext())
	{
	    Interceptor interceptor = InterceptorIterator.next();
	    try
	    {
		resultCode = interceptor.intercept(ActionInvocation.this);
	    }
	    catch (Exception e)
	    {
		e.printStackTrace();
	    }
	}
	return "fuck";
    }

    public Iterator<Interceptor> getIt()
    {
	return InterceptorIterator;
    }

    public void setIt(Iterator<Interceptor> it)
    {
	this.InterceptorIterator = it;
    }

    public Iterator<Interceptor> getInterceptorIterator()
    {
	return InterceptorIterator;
    }

    public void setInterceptorIterator(Iterator<Interceptor> interceptorIterator)
    {
	InterceptorIterator = interceptorIterator;
    }

    public String getResultCode()
    {
	return resultCode;
    }

    public void setResultCode(String resultCode)
    {
	this.resultCode = resultCode;
    }

}


4コール
  
 public static void main(String[] args)
    {
	ActionInvocation invocation = new ActionInvocation();
	
	List<Interceptor> list = new ArrayList<Interceptor>();
	Interceptor a = new InterceptorA();
	Interceptor b = new InterceptorB();
	Interceptor c = new InterceptorC();
	list.add(a);
	list.add(b);
	list.add(c);
	Iterator<Interceptor> it = list.iterator();
	invocation.setIt(it);
	invocation.invoke();
	System.out.println("end");

    }

実行結果:
begin A
begin B
begin C
before interceptor's resultCode : null
end C
before interceptor's resultCode : C
end B
before interceptor's resultCode : B
end A
end