java-如何在Struts 2中使用DispatcherListener

Struts2中有一个DispatcherListener接口.文档说

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

但是如何使用这个界面.如果创建实现该接口的类,应如何将其配置为Struts2?

解决方法:

实例化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 !!!
上一篇:Struts2


下一篇:java-Struts2-使用OGNL从静态列表设置字符串属性无法正常工作