zoukankan      html  css  js  c++  java
  • Struts2的DispatcherListener

    昨天在学习Struts2的代码时,发现在Dispatcher的init方法中,有这样一段代码:

    1 if (!dispatcherListeners.isEmpty()) {
    2                 for (DispatcherListener l : dispatcherListeners) {
    3                     l.dispatcherInitialized(this);
    4                 }
    5             }

    很明显,代码中的dispatcherListeners是Dispatcher的监听类,其作用无非就是在Dispatcher实例化和被销毁时调用监听类的相关方法。DispatcherListener的代码如下:

     1 /**
     2  * A interface to tag those that want to execute code on the init and
     3  * destory of a Dispatcher.
     4  */
     5 public interface DispatcherListener {
     6 
     7     /**
     8      * Called when the dispatcher is initialized
     9      *
    10      * @param du The dispatcher instance
    11      */
    12     public void dispatcherInitialized(Dispatcher du);
    13 
    14     /**
    15      * Called when the dispatcher is destroyed
    16      *
    17      * @param du The dispatcher instance
    18      */
    19     public void dispatcherDestroyed(Dispatcher du);
    20 }

    但是Dispatcher类是在server启动的时候被初始化的,那么如何在这个时候使用监听类呢?

    我们看下Dispatcher的相关代码:

     1 /**
     2      * Add a dispatcher lifecycle listener.
     3      *
     4      * @param listener The listener to add
     5      */
     6     public static void addDispatcherListener(DispatcherListener listener) {
     7         dispatcherListeners.add(listener);
     8     }
     9 
    10     /**
    11      * Remove a specific dispatcher lifecycle listener.
    12      *
    13      * @param listener The listener
    14      */
    15     public static void removeDispatcherListener(DispatcherListener listener) {
    16         dispatcherListeners.remove(listener);
    17     }

    在Dispatcher类里面,有两个静态的方法addDispatcherListener(DispatcherListener listener)removeDispatcherListener(DispatcherListener listener),而我在Struts2的初始化代码里面木有看到有调用这两个方法的代码。那么这个监听类只能是我们在使用Struts2时扩展用了。由于平时项目里根本碰不到类似这些底层的东西,不过结合自己的经验想了一下,可以这么做:

    ①,我们可以实现一个StrutsPrepareAndExecuteFilter的子类,我想一般的项目如果用到了struts2的话,肯定会自己扩展StrutsPrepareAndExecuteFilter的,那么我们可以在扩展类里面来调用这两个方法;

    ②,可以实现一个ServletContextListener的类,在这个类里面也可以调用我们自己实现的DispatcherListener的实现类。

    暂时,就想了这么多,其他应该还有很多方法,可以自己经验太浅,坑爹的对日外包。。。

  • 相关阅读:
    js数组的基本用法及数组根据下标(数值或字符)移除元素
    Oracle备份一张表
    linux中常见的文件操作命令
    java图片二进制相互转换
    getParameterMap的使用
    前端常用
    Oracle 常用
    JAVA中int、String的类型转换
    MySQL 5.7 新特性大全和未来展望
    你有自己的Web缓存知识体系吗?
  • 原文地址:https://www.cnblogs.com/huashui/p/struts2.html
Copyright © 2011-2022 走看看