Question

I have a Tomcat server deployed that receives observations transmitted from sensors in JSON format. I also have a sensor describing ontology that I want to make use of.

However, I'd like to load the ontology before any sensor observations are received by the server. How can I instantiate an object as soon as Tomcat is loaded?

Was it helpful?

Solution

To execute actions when your application starts or stops you should use a ServletContextListener: http://download.oracle.com/javaee/6/api/javax/servlet/ServletContextListener.html

In web.xml:

<web-app>
    ...
    <listener>
        <listener-class>com.example.Listener</listener-class>
    </listener>
    ...
</web-app>

In contrast to Peter Knego's proposal this solution is portable to any servlet container and not confined to Tomcat.

OTHER TIPS

I presume that strictly speaking, what you want to do is instantiate an object as soon as your servlet is loaded by Tomcat. (It wouldn't really make any sense to modify Tomcat itself for an application-specific functionality).

In this case, your Servlet class can override/implement the init(ServletConfig config) method. This is called by the servlet container (Tomcat in this case) when the servlet is initialised, and is exactly the right place to perform static startup logic, such as the kind you are referring to here.

In fact, the servlet will not even be able to receive connections until its init method has returned, so you can guarantee that the ontology will be fully loaded before the sensor observations arrive.

You could use event listeners which are invoked when the web app (contex) is loaded. There you initialize your objects and save them to ServletContext where they'll be available to all servlets in your app.

Implement ServletContextListener and in it's contextInitialized() put:

contextInitialized(ServletContextEvent sce){

    // Create your objects
    Object myObject = ...

    sce.getServletContext().setAttribute("myObjectKey", myObject);
} 

Then register the listener in Tomcat context.xml:

<Context path="/examples" ...>
    ...
    <Listener className="com.mycompany.mypackage.MyListener" ... >
    ...
</Context>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top