java getServletContext().getAttribute() 返回 null?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1444674/
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
getServletContext().getAttribute() returning null?
提问by moshen
When trying to set Context attributes like so:
当尝试像这样设置 Context 属性时:
void init()
{
String testing = new String();
testing = "This is a test";
getServletContext().setAttribute("test", testing);
}
In one servlet, and getting the attribute like so:
在一个 servlet 中,并像这样获取属性:
String testing = (String) getServletContext().getAttribute("test")
In a second servlet, testingis null.
在第二个 servlet 中,testing是null.
Does this mean my servlets are in separate contexts? If so, how could I access the context attributes of the first servlet? Please provide a reference for this as I am relatively new to java/servlets.
这是否意味着我的 servlet 位于不同的上下文中?如果是这样,我如何访问第一个 servlet 的上下文属性?请为此提供参考,因为我对 java/servlets 比较陌生。
I am using Netbeans with Glassfish 3.
我在 Glassfish 3 中使用 Netbeans。
EDIT: They are both in the same webapp and are both defined in the same WEB-INF/web.xml
编辑:它们都在同一个 webapp 中,并且都在同一个 WEB-INF/web.xml 中定义
回答by Arne Burmeister
If both servlets are in the same webapp, by default the order of initialization is undefined. So it may be, your "second" servlet is initialized before the "first" (according to the order in the web.xml). You may fix it by adding a load-on-startup tag to the servlet tag:
如果两个 servlet 在同一个 webapp 中,默认情况下初始化顺序是未定义的。因此,您的“第二个”servlet 可能在“第一个”之前初始化(根据 web.xml 中的顺序)。你可以通过在 servlet 标签中添加一个 load-on-startup 标签来修复它:
<servlet>
<servlet-name>first<servlet-name>
...
<load-on-startup>1<load-on-startup>
</servlet>
<servlet>
<servlet-name>second<servlet-name>
...
<load-on-startup>2<load-on-startup>
</servlet>
回答by Andy
I believe the two servlets need to be in the web application, i.e. packaged in the same war file, for this to work.
我相信这两个 servlet 需要在 web 应用程序中,即打包在同一个 war 文件中,这样才能工作。
回答by ZZ Coder
Context == WAR == webapps
上下文 == WAR == webapps
Both servlet has to live under the same webapp to share context. Check if both servlet classes are under same WEB-INF/classes.
两个 servlet 都必须在同一个 webapp 下共享上下文。检查两个 servlet 类是否在相同的 WEB-INF/classes 下。

