Expand my Community achievements bar.

BlazeDS servlet init() method

Avatar

Level 1

I want to set up some of my servlet variables (like for example MySQL database connection) at the BlazeDS startup. From what I've already found out, is that all of my  server side Java code constructors are invoked every time I'm calling any of it's class method. But what I'd want to do, is to write some kind of server side initialization method and run it only once, at the BlazeDS server startup, so I could initialize all kinds of "global" variables that will be used by all of the Flex clients, like database connection for example.

I've already found out a walkaround of this problem: I've put an if statement in the constructor, so it's not initializing anything for the second time. Plus, all of my variables are static, so their values are the same among all the Flex clients. Here's the sample code I've written:

public class Main  {

private static int count = -1;

public Main()
{
  if ( count == -1 ) count = 0; // that line guarantees that my count will be initialized (set at 0 at this example) only once in the servlet life time

}

public String echo()
{
  count++;
  return "Next count: "+count; // Every Flex client get's the next value (count++)
}

} // end of class

But I also know, that there's a better way to do it, using the init() method of my servlet. From what I found out reading some kind of Servlet's developents guides, is that I could replace the above code with something like this:

public class Main etends GenericServlet /* or HTTPServlet or MessageBrokerServlet */  {

private static int count = -1;

public void init(ServletConfig config) throws ServletException // this method should be launched only once in the servlet life time
{
  super.init(config);   
  count = 0;

}

public String echo()
{
  count++;
  return "Next count: "+count;
}

} // end of class

But somehow it's not working, and it seems that the init() method is never called at the startup. I'm not a Tomcat expert, but please anyone, what am I doing wrong?

0 Replies