Strutsで、一回ずつ初期化および終了処理を行うのがプラグイン。
サーブレットでは、init()およびdestroy()メソッドで初期化および終了処理を記述することが出来る。
Strutsを使う場合、基本的にサーブレットは(Strutsが提供している)ActionServletしか使わない。
そこで、プラグインという名前で、初期化および終了処理の呼び出し方法が用意されている。
プラグインを使う場合、StrutsのPlugInインターフェースを実装したクラスを用意する。
PlugInインターフェースにはinit()とdestroy()というメソッドがあり、ActionServlet#init()からプラグインのinit()が呼ばれ、ActionServlet#destroy()からプラグインのdestroy()が呼ばれる。
複数のプラグインを定義することが出来るが、それぞれのプラグインのメソッドが一度ずつ呼ばれる。
init()はstruts-config.xmlに記述された順序で、destroy()はinit()とは逆順で呼ばれる。
プラグインのinit()がServletException(UnavailableException)をスローすると、残りのプラグインのinit()は呼ばれず、ActionServletのinit()がその例外を再スローする。
struts-config.xmlのplug-in要素にプラグインのクラス名を指定する。
<struts-config> 〜 <plug-in className="jp.hishidama.sample.struts.SamplePlugIn"> <set-property property="prop1" value="value1" /> </plug-in> </struts-config>
set-property要素にproperty属性で名前を付けてvalue属性で値を指定することにより、プラグインクラスでその値を取得することが出来る。
package jp.hishidama.sample.struts;
import javax.servlet.ServletException; import org.apache.struts.action.ActionServlet; import org.apache.struts.action.PlugIn; import org.apache.struts.config.ModuleConfig;
public class SamplePlugIn implements PlugIn { protected String prop1; public void setProp1(String s) { prop1 = s; }
struts-config.xmlでのプラグインクラス指定時にset-property要素でプロパティーを指定する場合、プラグインクラス内にそのセッターメソッドを用意しておく。
@Override public void init(ActionServlet servlet, ModuleConfig config) throws ServletException { System.out.println("●SamplePlugIn#init(): " + prop1); } @Override public void destroy() { System.out.println("●SamplePlugIn#destroy()"); } }