开发者

Use of variables in ServletContextListener

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 lis开发者_开发问答tener 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;
   // ... 
}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜