How to use DispatcherListener in Struts 2

不羁岁月 提交于 2019-12-05 22:29:42

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 !!!

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!