gpt4 book ai didi

java - 从 Tomcat 应用程序中不同监听器之间的上下文获取属性

转载 作者:行者123 更新时间:2023-11-28 22:22:07 24 4
gpt4 key购买 nike

我有一个 Tomcat 7 webapp,其中有两个不同的 ServletContextListener

例子:

听众 A

public class ListenerA implements ServletContextListener {

public void contextInitialized(ServletContextEvent sce){

ObjectA objectA = new ObjectA();
context.setAttribute("objectA", objectA);
}

...

}

听众 B

public class ListenerB implements ServletContextListener {

public void contextInitialized(ServletContextEvent sce){

ObjectB objectB = new ObjectB();
context.setAttribute("objectB", objectB);
}

...

}

web.xml

...

<listener>
<description>ListenerA</description>
<listener-class>com.example.web</listener-class>
</listener>
<listener>
<description>ListenerB</description>
<listener-class>com.example.web</listener-class>
</listener>

...

¿web.xml 中出现的顺序是否会影响加载过程,或者它们是否在不同的线程中加载?

我想知道是否可以从 ListenerB 的上下文中获取 ObjectA。我总是可以将两个监听器合并为一个唯一的监听器,这样我就可以在同一个监听器中同时拥有对象 A 和 B,但我想知道这是否可能。

我知道我可以选择使用 ServletContextAttributeEvent 接口(interface)中的 attributeAdded,但是,如果 ListenerB 在听众A?

最佳答案

好的,所以我终于找到了答案 here

All servlet containers an J2EE 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.

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.

所以加载顺序严格按照web.xml中出现的顺序决定

关于java - 从 Tomcat 应用程序中不同监听器之间的上下文获取属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12816104/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com