1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

隠し機能:ActionEventListener

Posted at

隠し機能の1つ ActionEventListenerとは

ActionEventListenerとは、全てのActionクラスが実行される寸前と、例外が発生したときに実行する処理を記述するクラスです。現在のStruts2ではデフォルト実装はありません。

使い方

使うためには次の2つを行います。

  • ActionEventListenerインタフェースを実装したクラスを作る。
  • struts.xmlに作ったクラスを登録する。

ActionEventListenerを実装

この例は、以下の機能を実装しています。

  • Actionクラス実行前にログを出力する - prepare
  • 例外を検出した場合 - handleException
    • 例外クラスのインスタンスを調べ、DataIntegrityViolationExceptionであれば専用のログを出力する。
    • result値は常にActionSupport.ERRORを返す
SampleActionEventListener.java
public class SampleActionEventListener implements ActionEventListener {

	/**
	 * Action実行前に起動。
	 * @see com.opensymphony.xwork2.ActionEventListener#prepare(java.lang.Object, com.opensymphony.xwork2.util.ValueStack)
	 */
	@Override
	public Object prepare(Object action, ValueStack stack) {

		log.debug("prepare.");

		return action;
	}

	/**
	 * 例外発生時の制御。
	 * @see com.opensymphony.xwork2.ActionEventListener#handleException(java.lang.Throwable, com.opensymphony.xwork2.util.ValueStack)
	 */
	@Override
	public String handleException(Throwable t, ValueStack stack) {

		log.debug(" = handling exception =");

		if ( t instanceof DataIntegrityViolationException) {
			log.warn(" -- cause DataIntegrityViolationException:{}" , t);
		}

		return ActionSupport.ERROR;
	}
}

struts.xmlに登録

ActionEventListenerを実装したクラスを設定ファイルであるstruts.xmlに追加します。

struts.xml
<struts>
	<!-- ActionEventListener -->
	<bean type="com.opensymphony.xwork2.ActionEventListener" class="sample.app.SampleActionEventListener"/>
</struts>

隠し機能となった経緯

このActionEventListenerを有効にすると全てのActionクラスに対して有効になります。Struts2と言えばAction回りの共通処理は全てインターセプタで提供されるものであり、事実このリスナークラスはActionクラスの動作を行うDefaultActionInvocationクラスからのみ制御されて動作しますので、Struts2のポリシーからは逸脱した制御です。

また、ActionEventListenerで実装するprepare()メソッドはPrepare Interceptorが存在し、このインターセプタによりActionごとに前処理を定義できます。例外ハンドリングもexceptionMappingがstruts.xmlやConventionプラグインのResultMappingsで個別に行えます。

同一の機能がStruts2によって提供されており、Actionクラスごとに制御できることもあって、ActionEventListenerは現在使いません。
もし全クラスに共通する制御を行いたい場合にのみActionEventListenerを使いましょう。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?