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 dont 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配置文件讲解”。
