I have a Spring servlet called with load-on-startup = 1 and it requires a database connection, but sometimes, connection is null and the appLoader servlet fails. The connection is null because tomcat didn't had the time to load the global resources properly.
Question : How do I ask Spring to wait for jndi proper loading? I mean, order it in some way.
Dirty solution : Make another servlet with active wait and waiting for a working connection before calling my appLoader...
1) The job of <load-on-startup>
is to start a servlet at the time of deployment. It just initiates(starts
) the process after that it has no control over that servlet.
The entire control of the started servlet is in the hands of the web container
.
The behaviour of the web container can be programmatically controlled using Event Handling mechanism.
2) Events are basically occurrence of something. Changing the state of an object is known as an event.
2.1) You can handle the events of web container
using event listeners of servlet and perform some important tasks such as creating tables of the database, creating database connection object etc. at time of deploying the project.
There are many Event classes and Listener interfaces in the javax.servlet
and javax.servlet.http
package.
You can use ServletContextListener
to store the connection object
in the context attribute and later fetch that connection object from servlet context.
Here are few examples where database connection object is stored in servlet context. example1 example2 example3
2.2) You can use Event Handling mechanism of spring framework.
In spring you can poll your database connection using ContextStartedEvent
that is raised when an ApplicationContext
gets started.
Here, are some spring events with example.