Tuesday, September 2, 2014

How to launch and run a Java program/servlet automatically on Tomcat Server startup

Over the weekend I did some serious server side optimization and I really wanted to have a servlet launch when my server restarted. I wasn't sure how to do this, but I was sure it was possible. After looking it up, I realized its quite simple. So to save you some time I have explained it below :)

To run a servlet automatically on Tomcat Startup you have to use a servlet that is initialized to startup automatically. We do this in the deployment descriptor web.xml file in WEB-INF. 
To create a web.xml file for your package follow the directions below:
  1. Go to your Dynamic Web Project and right click
  2.  Select Java EE Tools and choose to Generate Deployment Descriptor Stub.


The web.xml file must contain tags <load-on-startup> and <servlet>. The Servlet tag will store the information of Servlet class. When tomcat starts, all the Servets load and the "init" method of the servlet runs first. This can be convenient for initialization of variables or setting up data structures. 


No comments:

Post a Comment

SUBSCRIBE

Pages - Menu

Pages

top social

SUBSCRIBE

About