I have a Servlet which is annotated like this:
@WebServlet(value="/MyServiceServlet", loadOnStartup=1)
This results in the Servlet being instantiated on application start and its init()
method being called. Perfect! (In the init()
method, a Thread is started to perform some db maintenance which runs each hour)
Now, on certain end user actions, I reach the Servlet by using
getServletContext().getRequestDispatcher("/MyServiceServlet").include(request, response)
to trigger some other db stuff, but the first time I try this, my Servlet gets instantiated one more time and the init()
method is called (of course), which results in two similar Threads running. Not perfect!
It seems as if the loadOnStartup=1
does not put the Servlet in the Servlet Context, hence when I try to reach it by the Request Dispatcher it needs to be instantiated.
How can this be? How to fix so I just get one instance of my Servlet? I need it to be started along the application, as the Service started in the init()
should run immediately.
The application is deployed on Tomcat 7.0.57.