如何在Struts 2中使用DispatcherListener [英] How to use DispatcherListener in Struts 2
问题描述
Struts2中有一个接口 DispatcherListener
。文档说
There is a interface DispatcherListener
in Struts2. The docs says
标记那些想要在
init $ c $上执行代码的接口c>和
销毁
。Dispatcher
的
"A interface to tag those that want to execute code on the
init
anddestroy
of aDispatcher
."
但是如何使用这个界面。如果我创建一个实现此接口的类,我应该如何配置它为Struts2?
But how to use this interface. If I create a class that implements this interface, how should I configure it to Struts2?
推荐答案
当 Dispatcher
被实例化,它可以在初始化或销毁时发送给监听器通知。参考和代码示例来自此处。
When a Dispatcher
is instantiated, it could send to the listener notification when it's initialized or destroyed. The reference and code samples are from here.
简单的用法是通过容器通过 bean
标签实例化bean并将其自身添加到 init
方法并在销毁时删除自己,就像 ClasspathConfigurationProvider
。
The simple usage is to instantiate a bean by the container via bean
tag and add themselves in the init
method and remove themselves when destroyed like it did by the ClasspathConfigurationProvider
.
代码原始只是为了向您展示这个想法
The code is raw just for to show you the idea
struts.xml
:
struts.xml
:
<bean type="com.opensymphony.xwork2.config.PackageProvider" name="myBean" class="jspbean.struts.MyBean" />
MyBean.java
:
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 !!!
这篇关于如何在Struts 2中使用DispatcherListener的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!