Struts2中有一个接口DispatcherListener
。文档说
“标记那些想要在
init
上执行代码的接口destroy
的{{1}}。
但是如何使用这个界面。如果我创建一个实现此接口的类,我应该如何配置它为Struts2?
答案 0 :(得分:2)
当Dispatcher
被实例化时,它可以在初始化或销毁时向监听器发送通知。参考和代码示例来自here。
简单的用法是通过bean
标记通过容器实例化bean,并在init
方法中添加自己,并在销毁时将其自身移除,就像ClasspathConfigurationProvider
一样。
代码原始只是为了向您展示这个想法
<强> struts.xml
强>
<bean type="com.opensymphony.xwork2.config.PackageProvider" name="myBean" class="jspbean.struts.MyBean" />
<强> MyBean.java
强>
public class MyBean implements ConfigurationProvider, DispatcherListener {
public MyBean() {
System.out.println("!!! MyBean !!!");
}
@Override
public void dispatcherInitialized(Dispatcher du) {
System.out.println("!!! dispatcherInitialized !!!");
}
@Override
public void dispatcherDestroyed(Dispatcher du) {
System.out.println("!!! dispatcherDestroyed !!!");
}
@Override
public void destroy() {
System.out.println("!!! destroy !!!");
Dispatcher.removeDispatcherListener(this);
}
@Override
public void init(Configuration configuration) throws ConfigurationException {
System.out.println("!!! init !!!");
Dispatcher.addDispatcherListener(this);
}
@Override
public boolean needsReload() {
return false;
}
@Override
public void loadPackages() throws ConfigurationException {
}
@Override
public void register(ContainerBuilder builder, LocatableProperties props) throws ConfigurationException {
}
}
输出:
15:27:50 INFO (org.apache.struts2.spring.StrutsSpringObjectFactory:42) - ... initialized Struts-Spring integration successfully
!!! MyBean !!!
!!! init !!!
jul 18, 2013 3:27:51 PM org.apache.catalina.startup.HostConfig deployDirectory
!!! dispatcherInitialized !!!
[2013-07-18 06:28:11,102] Artifact jspbean:war exploded: Artifact is deployed successfully
INFO: A valid shutdown command was received via the shutdown port. Stopping the Server instance.
INFO: Stopping service Catalina
!!! dispatcherDestroyed !!!
答案 1 :(得分:1)
如果您正在使用Spring,那么您可以创建监听器的bean,并在构造函数中将其添加到dispatcherListeners
列表。
public YourDispatcherListener () {
Dispatcher.addDispatcherListener(this);
}
另一种解决方案是创建ServletContextListener
,创建您的调度程序侦听器并将其添加到列表中。