Create an object when Tomcat starts

I have a Tomcat server installed, which receives observations transmitted from sensors in JSON format. I also have a sensor describing the ontology that I want to use.

However, I would like to download the ontology before any sensor observations are received by the server. How can I instantiate an object as soon as Tomcat boots up?

+4
source share
3 answers

To perform actions when the application starts or stops, you must use 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> 

Unlike Peter Knego's offer, this solution is ported to any servlet container and is not limited to Tomcat.

+7
source

I assume that, strictly speaking, you want to instantiate an object as soon as your servlet is loaded by Tomcat. (In fact, it would not make sense to modify Tomcat for application-specific functions).

In this case, your Servlet class can override / implement the init(ServletConfig config) method init(ServletConfig config) . This is caused by the servlet container (Tomcat in this case) when the servlet is initialized, and this is exactly where you need to execute the static startup logic, such as the view you are talking about here.

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

+1
source

You can use event listeners that are triggered when a web application is loaded (context). There you initialize your objects and save them to ServletContext , where they will be available to all servlets in your application.

Insert ServletContextListener and in it contextInitialized() put:

 contextInitialized(ServletContextEvent sce){ // Create your objects Object myObject = ... sce.getServletContext().setAttribute("myObjectKey", myObject); } 

Then register the listener in the context of Tomcat.xml:

 <Context path="/examples" ...> ... <Listener className="com.mycompany.mypackage.MyListener" ... > ... </Context> 
0
source

All Articles