tags:

views:

494

answers:

3

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

A: 

I believe the two servlets need to be in the web application, i.e. packaged in the same war file, for this to work.

Andy
A: 

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.

ZZ Coder
They are both in the same webapp and are both defined in the same WEB-INF/web.xml
moshen
+3  A: 

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>
Arne Burmeister
Thank you!! This seems to work. This has been driving me crazy all morning. Do you happen to know why this matters?
moshen