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的实现类。

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

 

posted @   画水  阅读(388)  评论(0编辑  收藏  举报
编辑推荐:
· 软件产品开发中常见的10个问题及处理方法
· .NET 原生驾驭 AI 新基建实战系列:向量数据库的应用与畅想
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
· 一次Java后端服务间歇性响应慢的问题排查记录
· dotnet 源代码生成器分析器入门
阅读排行:
· ThreeJs-16智慧城市项目(重磅以及未来发展ai)
· .NET 原生驾驭 AI 新基建实战系列(一):向量数据库的应用与畅想
· Ai满嘴顺口溜,想考研?浪费我几个小时
· Browser-use 详细介绍&使用文档
· 软件产品开发中常见的10个问题及处理方法
点击右上角即可分享
微信分享提示