tags:

views:

42

answers:

2

Is there any reason why a variable can't be created in a Java ServletContextListener and it's value set and get like any other. What I have is an ArrayList in an SCL and a method in another class updates the ArrayList every so often using static get and set methods in the SCL itself. My preference here is not to use ServletContext to store the ArrayList.

No new instance of the listener is ever created at all.

Code in the SCL is similar to below:

private static ArrayList<String> strList;

@Override
public void contextInitialized(ServletContextEvent contextEvent) { 
    ArrayList<String> temp = someOtherMethod(); 
    setStrList(temp);
}

@Override
public void contextDestroyed(ServletContextEvent contextEvent) {        
}

public static ArrayList<String> getStrList() {
   // ...
   return strList;
}

public static void setStrList(ArrayList<String> temp) {
   this.strList = temp;
   // ... 
}
+2  A: 

Your "variable" has to live somewhere that you can get to it.

If you're in a ContextListener then you can put an object into the ServletContext and get it back later from anything else that has access to the same ServletContext. Having gotten it, you can of course update it too, if it's mutable like an ArrayList.

Carl Smotricz
A: 

This will fail in webapplications which are served by a cluster of servers running its own JVM. This way each server will have its own list, because static variables are JVM-bound. Rather store it in ServletContext. In a well-configured cluster this will be replicated. The ServletContext is available everywhere in the webapp, so I don't see the benefit of making the variable static.

BalusC
But what if there is only one server for the application? it is a student project, not a full blown real world application.
Mr Morgan
It's then called a bad practice. If your tutor is smart, you'll lose points. If not, it might hang and you might unawarely reapply the same bad practice in real world because "it worked" when you was a full blown student.
BalusC