您可以繼承ActionServlet,重新定義它的init()方法,這樣可以在ActionServlet被載入時增加一些您想要載入的資源,然而這並不是個好方法,您必須將程式碼寫死在當中,如果您要載入的資源多時是一個麻煩,想要拆除某個資源時又是一個麻煩。
Struts 1.1提供一個新的PlugIn介面,它可以讓您動態增減ActionServlet的功能,PlugIn中規定了兩個必須實作的方法:
public interface PlugIn { 
public void init(ActionServlet servlet,
ModuleConfig config)
throws javax.servlet.ServletException;
public void destroy();
}
      
      
 public void init(ActionServlet servlet,
ModuleConfig config)
throws javax.servlet.ServletException;
public void destroy();
}
您可以將資源載入的動作撰寫在init()方法中,ActionServlet會載入後,會執行實作PlugIn介面的類別之 init()方法,例如您可以在這邊進行資料庫資源的連結,而ActionServlet被終結前,會執行實作PlugIn介面的類別之destroy ()方法,您可以在這邊撰寫一些釋放資源的方法。
實作PlugIn介面時,必須提供一個沒有參數的建構函式給ActionServlet使用,如果初始化需要一些參數設定,您可以如同JavaBean一樣的設定setter,一個實例的例子如下:
- MyPlugin.java
package onlyfun.caterpillar; 
 
....... 
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) { 
         ... 
    } 
}為了讓ActionServlet知道要「掛上」這個PlugIn,您要在struts-config.xml中設定:
<plug-in className="onlyfun.caterpillar.MyPlugIn"> 
<set-property
property="XXX"
value="abcde"/>
</plugin>
       
      
      
如果您在某個 Action 中必須使用到「掛上」的資源,您可以由Action的Field成員servlet(ActionServlet物件)來取得 ServletContext,並取出所必須的資源,例如:<set-property
property="XXX"
value="abcde"/>
</plugin>
public ActionForward execute(ActionMapping mapping, 
Actionform form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception {
.......
ServletContext context = servlet.getServletContext();
SomeService service =
(SomeService) context.getAttribute("service");
......
}
      
      
 Actionform form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception {
.......
ServletContext context = servlet.getServletContext();
SomeService service =
(SomeService) context.getAttribute("service");
......
}
像Tiles、Validator等都是利用這種方式來擴充Struts的功能。

