简体   繁体   中英

getServletContext().getAttribute() returning null?

When trying to set Context attributes like so:

void init()
{
    String testing = new String();
    testing = "This is a test";
    getServletContext().setAttribute("test", testing);
}

In one servlet, and getting the attribute like so:

String testing = (String) getServletContext().getAttribute("test")

In a second servlet, testing is 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.

I am using Netbeans with Glassfish 3.

EDIT: They are both in the same webapp and are both defined in the same WEB-INF/web.xml

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

Both servlet has to live under the same webapp to share context. Check if both servlet classes are under same WEB-INF/classes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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