3.Struts Plugins: Plugin从Struts1.1开始介绍,它定义了一个org.apache.struts.action.Plugin接口,它主要用来分配资源(allocating resources)或者建立数据库的连结或者JNDI资源。这个接口提供了两个必须实现的方法:init()和destroy()。如果运用了Plugin技术,那么在容器启动的时候,会调用Plugin的init()方法。所以将应用系统的初始化信息写在这里。当容器停止Struts应用系统的时候,会调用destroy()方法,destroy()方法主要是用来收回在init()方法中分配的资源信息。 ◆扩展Plugin类 ① 创建一个实现Plugin接口的类 ② 添加一个空的构造器 ③ 实现init()及destroy()两个方法 ④ 在struts-config.xml文件中对<plug-in />元素的配置 创建Plugin必须继承org.apache.struts.action.Plugin接口。并且实现init()及destroy()方法。例子: package wiley;
import java.util.Properties; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.ServletContext; import org.apache.struts.action.PlugIn; import org.apache.struts.config.ModuleConfig; import org.apache.struts.action.ActionServlet;
public class WileyPlugin implements PlugIn {
public static final String PROPERTIES = "PROPERTIES";
public WileyPlugin() {}
public void init(ActionServlet servlet, ModuleConfig config) throws javax.servlet.ServletException { System.err.println("....>The Plugin is starting<...."); Properties properties = new Properties(); String path = "C:\\ApplicationResources"+ ".properties"; try { // Build a file object referening the properties file // to be loaded File file = new File(path); // Create an input stream FileInputStream fis = new FileInputStream(file); // load the properties properties.load(fis); // Get a reference to the ServletContext ServletContext context = servlet.getServletContext(); // Add the loaded properties to the ServletContext // for retrieval throughout the rest of the Application context.setAttribute(PROPERTIES, properties); } catch (FileNotFoundException fnfe) { throw new ServletException(fnfe.getMessage()); } catch (IOException ioe) { throw new ServletException(ioe.getMessage()); } }
public void destroy() { // We don't have anything to clean up, so // just log the fact that the Plugin is shutting down System.err.println("....>The Plugin is stopping<...."); } } ◆配置Plugin: 在struts-config.xml文件中配置<plug-in>元素。如下: <plug-in className=”wiley.WileyPlugin” /> <plug-in />的详细配置信息见”struts-config.xml配置文件讲解”。
|