I started off by extending
GenericServletand overriding the
destroymethods to write log messages to standard out. Then I wrote the appropriate
web.xmlto tell Tomcat about the servlet and wrapped it all up in a
warfile (basically a zip file with a Tomcat specific directory layout) and deployed it to my local Tomcat installation. I then checked the logs and found the log messages I'd put in the code. Not bad going for twenty minutes work and my first Tomcat servlet written from scratch.
We've been gradually learning about Spring recently and I remembered reading that Spring had timers that would be perfect for polling the directory for files. So I integrated Spring into my servlet, repackaged and redeployed it and then checked the logs to make sure the Spring application context had fired up correctly. It had.
Next I created a
Tickerclass by implementing the Java
TimerTaskinterface and implementing the
runmethod to write "Tick" to standard out. I then registered the class as a Spring bean and created a Spring
ScheduledTimerTask, set the tick interval to one second and created an anonymous
TimerFactoryBean. Making the
TimerFactoryBeananonymous causes it to be instantiated when the Spring context is started, rather than waiting for an explicit instantiation from code somewhere. So, what should happen is that the ticker should start as soon as the application starts. Sure enough as soon as I repackaged and deployed, "Tick" was written to standard out every second.
It occurred to me that the class extending
GenericServletwas redundant. So, not expecting it to work, I removed the class from the servlet and
web.xmlentirely and repackaged and redeployed. That's when I had my real "Whoah! That's really neat!" moment. To my amazement and joy the ticker started again and kept ticking every second. I already knew Spring and Tomcat worked well together, but having Tomcat start the Spring context without needing a servlet class is pure genius.
It may seem like such a small and simple thing, but creating my first Java service and Spring timer and having them work together in a very simple way was a real revelation for me.