简体   繁体   English

getServletContext()。getAttribute()返回null吗?

[英]getServletContext().getAttribute() returning null?

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, testing is null . 在第二个servlet中, testingnull

Does this mean my servlets are in separate contexts? 这是否意味着我的servlet在单独的上下文中? If so, how could I access the context attributes of the first servlet? 如果是这样,我如何访问第一个servlet的上下文属性? Please provide a reference for this as I am relatively new to java/servlets. 请为此提供参考,因为我是java / servlet的新手。

I am using Netbeans with Glassfish 3. 我正在将Netbeans与Glassfish 3一起使用。

EDIT: They are both in the same webapp and are both defined in the same WEB-INF/web.xml 编辑:它们都在同一个webapp中,并且都在同一个WEB-INF / web.xml中定义

If both servlets are in the same webapp, by default the order of initialization is undefined. 如果两个Servlet都在同一个Web应用程序中,则默认情况下,初始化的顺序是不确定的。 So it may be, your "second" servlet is initialized before the "first" (according to the order in the web.xml). 可能是这样,您的“第二个” servlet在“第一个” servlet之前初始化(根据web.xml中的顺序)。 You may fix it by adding a load-on-startup tag to the servlet tag: 您可以通过在servlet标签中添加启动时加载标签来解决此问题:

<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>

我相信这两个servlet必须在Web应用程序中,即包装在同一个war文件中,才能起作用。

Context == WAR == webapps 上下文== WAR == webapps

Both servlet has to live under the same webapp to share context. 两个Servlet都必须生活在同一个Web应用程序下才能共享上下文。 Check if both servlet classes are under same WEB-INF/classes. 检查两个servlet类是否都在相同的WEB-INF /类下。

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

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