public interface PlugIn { public void init(ActionServlet servlet, ModuleConfig config) throws javax.servlet.ServletException; public void destroy(); }您可以将资源加载的动作撰写在init()方法中,ActionServlet会加载后,会执行实作PlugIn接口的类别之 init()方法,例如您可以在这边进行数据库资源的连结,而ActionServlet被终结前,会执行实作PlugIn接口的类别之destroy ()方法,您可以在这边撰写一些释放资源的方法。
package onlyfun.caterpillar;为了让ActionServlet知道要「挂上」这个PlugIn,您要在struts-config.xml中设定:
.......
import org.apache.struts.action.*;
public class MyPlugIn implements PlugIn {
......
public MyPlugIn() {
}
public void init(ActionServlet servlet,
ModuleConfig config)
throws javax.servlet.ServletException {
// 初始化資源
SomeService service = new SomeService();
......
servlet.getServletContext().setAttribute("service", service);
}
public void destroy() {
// 釋放資源
}
public void setXXX(String xxx) {
...
}
}
<plug-in className="onlyfun.caterpillar.MyPlugIn"> <set-property property="XXX" value="abcde"/> </plugin>如果您在某个 Action 中必须使用到「挂上」的资源,您可以由Action的Field成员servlet(ActionServlet对象)来取得 ServletContext,并取出所必须的资源,例如:
public ActionForward execute(ActionMapping mapping, Actionform form, HttpServletRequest request, HttpServletResponse response) throws Exception { ....... ServletContext context = servlet.getServletContext(); SomeService service = (SomeService) context.getAttribute("service"); ...... }
像Tiles、Validator等都是利用这种方式来扩充Struts的功能。