Skip to content
Advertisement

How to use DispatcherListener in Struts 2

There is a interface DispatcherListener in Struts2. The docs says

“A interface to tag those that want to execute code on the init and destroy of a Dispatcher.”

But how to use this interface. If I create a class that implements this interface, how should I configure it to Struts2?

Advertisement

Answer

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 !!!
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement