moshen
moshen

Reputation: 1124

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

Upvotes: 3

Views: 11897

Answers (3)

Arne Burmeister
Arne Burmeister

Reputation: 20614

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>

Upvotes: 6

ZZ Coder
ZZ Coder

Reputation: 75496

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.

Upvotes: 0

Andy
Andy

Reputation: 9058

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

Upvotes: 0

Related Questions