Struts插件plug-in标签元素的作用
问题: 有时候你需要在应用程序启动时装载一些数据到程序上下文中或执行某些操作。
解决方法: 创建一个实现了org.apache.struts.action.PlugIn接口的类文件并在struts-config.xml中设置plug-in元素。以下代码片段显示了一个plug-in生命声明和一个自定义的set-property子元素:
<plug-in className="com.oreilly.strutsckbk.CustomPlugin" > <set-property property="customData" value="Hello from the plugin"/></plug-in>
package org.apache.struts.action; import javax.servlet.ServletException; import org.apache.struts.config.ModuleConfig; public interface PlugIn { void destroy(); void init(ActionServlet servlet, ModuleConfig config) throws ServletException; }
TimeTracker.java:package com.yourcompany.struts.plugin;import java.util.Date;public class TimeTracker { private long startUpTimeMillis; private Date startedOn; public TimeTracker( ) { startUpTimeMillis = System.currentTimeMillis( ); startedOn = new Date( ); } public long getUptime( ) { return System.currentTimeMillis( ) - startUpTimeMillis; } public Date getStartedOn( ) { return startedOn; }}
TimeTrackerPlugin.java:package com.yourcompany.struts.plugin;import javax.servlet.ServletException;import org.apache.struts.action.ActionServlet;import org.apache.struts.action.PlugIn;import org.apache.struts.config.ModuleConfig;public class TimeTrackerPlugin implements PlugIn { private String contextKey; public void setContextKey(String key) { this.contextKey = key; } public void init(ActionServlet servlet, ModuleConfig conf) throws ServletException { servlet.getServletContext( ).setAttribute(contextKey, new TimeTracker( )); } public void destroy( ) { }}
struts-config.xml: <plug-in className="com.yourcompany.struts.plugin.TimeTrackerPlugin"> <set-property property="contextKey" value="timeTracker"/> </plug-in>