Reputation: 1858
There is a interface DispatcherListener
in Struts2. The docs says
"A interface to tag those that want to execute code on the
init
anddestroy
of aDispatcher
."
But how to use this interface. If I create a class that implements this interface, how should I configure it to Struts2?
Upvotes: 3
Views: 1799
Reputation: 1
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.
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
:
<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 {
}
}
The output:
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 !!!
Upvotes: 2
Reputation: 24396
If you are using Spring then you can create bean of your listener and in constructor add it to dispatcherListeners
list.
public YourDispatcherListener () {
Dispatcher.addDispatcherListener(this);
}
Another solution is to create ServletContextListener
which creates your dispatcher listener and adds it to list.
Upvotes: 1