简体   繁体   English

如何在web.xml中确定侦听器的顺序

[英]How to determine the order of listeners in web.xml

I got a bunch of servlet context listeners in my Java webapp, each of them gathering some information about the environment. 我的Java webapp中有一堆servlet上下文监听器,每个都收集一些有关环境的信息。

Some of them depend on information which is gathered by another listener. 其中一些依赖于另一个听众收集的信息。 But I can't determine the order in which the listeners are registered and called, so I have to duplicate code. 但我无法确定监听器的注册和调用顺序,因此我必须重复代码。

I understand that the listeners are registered in the order their order in web.xml but this sounds a bit vague to me, too vague to rely on it. 我理解听众是按照他们在web.xml中的顺序注册的,但这对我来说听起来有些模糊,过于模糊,无法依赖它。

Do you have a hint how I can solve my problem? 你有提示我如何解决我的问题吗?

All servlet containers and Java EE containers implement this part of the spec strictly. 所有servlet容器和Java EE容器都严格执行规范的这一部分。 You can rely on the fact that the listeners are called in the order you specified in web.xml. 您可以依赖于按照您在web.xml中指定的顺序调用侦听器的事实。

You can have a Application LEVEL Data structure(HashMap) that will be updated by each Filter/Listener as it encounters the data from the requests. 您可以拥有一个Application LEVEL数据结构(HashMap),每个Filter / Listener在遇到请求数据时都会对其进行更新。 This will let each Listener update only what is essential. 这将让每个Listener只更新必要的内容。 You can put the common code in a base Listener so that there is no code duplication. 您可以将公共代码放在基本侦听器中,以便不存在代码重复。

Why is that vague? 为什么这模糊? The ordering in web.xml is very specifically the order in which they are called, it's very clearly stated in the Java EE spec. web.xml中的排序非常具体地是它们被调用的顺序,它在Java EE规范中非常清楚地说明。 It's completely OK to rely on it. 依靠它完全可以。

It would seem you can create a ListenerManager which you place as your one and only listener, and have it contain the other Listeners. 看起来你可以创建一个ListenerManager,你将它作为唯一的监听器,并让它包含其他监听器。 When the event comes in, simply call each of the other Listeners in the order you require (probably the order you created them in the ListenerManager's constructor). 当事件进入时,只需按照您需要的顺序调用其他每个监听器(可能是您在ListenerManager的构造函数中创建它们的顺序)。

Unfortunately, this means a code change when you add Listeners, but you can avoid this through clever use of properties files and create-from-class-name code. 不幸的是,这意味着在添加Listeners时会更改代码,但是您可以通过巧妙地使用属性文件和create-from-class-name代码来避免这种情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM