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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/178562/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 10:57:00  来源:igfitidea点击:

How to determine the order of listeners in web.xml

javaservletsjakarta-ee

提问by Olvagor

I got a bunch of servlet context listeners in my Java webapp, each of them gathering some information about the environment.

我的 Java web 应用程序中有一堆 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?

你有什么提示我可以解决我的问题吗?

采纳答案by anjanb

All servlet containers and Java EE containers implement this part of the spec strictly. You can rely on the fact that the listeners are called in the order you specified in web.xml.

所有 servlet 容器和 Java EE 容器都严格实现了规范的这一部分。您可以依赖这样一个事实,即按照您在 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. This will let each Listener update only what is essential. You can put the common code in a base Listener so that there is no code duplication.

您可以拥有一个应用程序级别数据结构(HashMap),每个过滤器/侦听器在遇到来自请求的数据时都会更新该结构。这将让每个 Listener 只更新必要的内容。您可以将公共代码放在基本侦听器中,这样就不会出现代码重复。

回答by billjamesdev

It would seem you can create a ListenerManager which you place as your one and only listener, and have it contain the other Listeners. 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 并将其放置为您唯一的监听器,并让它包含其他监听器。当事件发生时,只需按照您需要的顺序(可能是您在 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.

不幸的是,这意味着当您添加侦听器时代码会发生变化,但是您可以通过巧妙地使用属性文件和从类名创建代码来避免这种情况。

回答by skaffman

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. It's completely OK to rely on it.

为什么这么含糊?web.xml 中的顺序是它们被调用的非常具体的顺序,它在 Java EE 规范中有非常明确的说明。完全可以依赖它。