22. アノテーションによるAction,Resultの前後処理

WebWork2.2で以下のアノテーションサポートが追加されました。

  • Interceptor Annotations
  • Validation Annotations
  • Type Conversion Annotations

下の2つは設定ファイルで書いた方が楽だと思いますが(^^;、Interceptor Annotationsは便利なので紹介します。
これはアノテーションによって、Action,Resultの前後で行う処理を指定する機能になります。

設定(ライブラリ)

まずはJavaSE5.0関連の機能を使うために、xwork-tiger.jarをクラスパスに追加します。

設定(xwork.xml)

AnnotationWorkflowInterceptorを定義してActionに設定します。

<interceptors>
  <interceptor name="annotationWorkflow"
    class="com.opensymphony.xwork.interceptor.annotations.AnnotationWorkflowInterceptor"/>
</interceptors>
<action name="annotation" class="ww2.examples.event.AnnotationAction">
  <interceptor-ref name="annotationWorkflow"/>
</action>

AnnotationAction

アノテーションは@Before,@BeforeResult,@Afterの3つありそれぞれ以下のタイミングで実行されます。

@Before
execute()メソッド実行の前
@BeforeResult
execute()メソッド実行後、Result実行前
@After
Result実行後
public class AnnotationAction extends ActionSupport {
    @Override
    public String execute()  {
        System.out.println("execute");
        return SUCCESS;
    }

    @Before
    public void before() {
        System.out.println("before");
    }

    @BeforeResult
    public void beforeResult() {
        System.out.println("beforeResult");
    }

    @After
    public void after() {
        System.out.println("after");
    }

}

結果

以下の順番で実行されます。

感想

Resultの実行後に処理を行う方法が無かったので、これが提供されたのはうれしいです。
一つのActionに複数メソッドある場合の前後処理など色々使い道がありそうです。