アクションメソッドの前後処理を記述する(@Before/@After/@BeforeResultアノテーション)
<interceptor name="annotationInterceptor" class="com.opensymphony.xwork2.interceptor.annotations.AnnotationWorkflowInterceptor"/>
<interceptor-ref name="annotationInterceptor"/>
Actionクラス
public class BeforeAfterAction extends ActionSupport { @Before public void before(){ System.out.println("@before"); } @After public void after() { System.out.println("@after"); } @BeforeResult public void beforeResult() { System.out.println("@beforeResult"); } @Override public String execute(){ System.out.println("@execute"); return SUCCESS; } }
このActionにアクセスすると、
@before @execute @beforeResult @after
こんな順番で処理されていました。
じゃあためしに、Validationでエラーにしてみる
public class BeforeAfterAction extends ActionSupport { private String id; public String getId() { return id; } @RequiredStringValidator(message="") public void setId(String id) { this.id = id; } @Before public void before(){ System.out.println("@before"); } @After public void after() { System.out.println("@after"); } @BeforeResult public void beforeResult() { System.out.println("@beforeResult"); } @Override public String execute(){ System.out.println("@execute"); return SUCCESS; } }
すると、
@before @beforeResult @after
こんな感じ。
使い道としては、認証チェックとかログ出力でしょうか。
ちなみに、after()に
@After public void after() throws Exception { System.out.println("@after"); ActionInvocation invocation = ActionContext.getContext().getActionInvocation(); System.out.println(invocation.getResultCode()); }
こんな風に書くと、結果コードが取得できます。
結果コードには、通常は実行されたActionメソッドの戻り値の文字列がはいっていますが、
(今回の例の場合は、executeメソッドの戻り値「success」)
Validationでエラーの場合は「input」になります。
ここで、試しにこんなことしてみた
@After public void after() throws Exception { System.out.println("@after"); ActionInvocation invocation = ActionContext.getContext().getActionInvocation(); invocation.setResultCode(SUCCESS); //無理やりSUCCESS!! System.out.println(invocation.getResultCode()); }
すると、きっちりExceptionが発生しました。
java.lang.IllegalStateException: Result has already been executed.