Recently I wanted to start my standalone Java Application on Tomcat Startup. Also found so many other related questions on net. i.e.
- I need to run an application that can run automatically that when the tomcat starts..? any suggestions…?
- how can I start my application by default on tomcat server start/restart?
- Is it possible to edit tomcat startup services?
To run java program automatically on tomcat startup, need to use Servlet and this Servlet initialized on tomcat startup automatically.
To execute our program, we have to use Servlet and Servlet should define in deployment descriptor web.xml file in WEB-INF. web.xml file contain tags <load-on-startup> and <servlet>tag. Servlet tag keep information of Servlet class. When tomcat starts, all Servlet loads in web container and init method of Servlet loaded first. Any java statement in init method of Servlet can be executed on running tomcat startup batch or shell.
In init method we can define our scripts which have to be executed e.g. sending emails, sending newsletters, starting scheduler, etc..
Below is a simple trick to run your java program automatically on Tomcat Startup.
1) Modify Web.xml file with below information. Where CrunchifyExample is a class name and com.crunchify.tutorials is a package name. Modify these values as per your need.
<servlet> <servlet-name>CrunchifyExample</servlet-name> <servlet-class>com.crunchify.tutorials</servlet-class> <load-on-startup>1</load-on-startup> </servlet>
package com.crunchify.tutorials; import javax.servlet.*; import javax.servlet.http.HttpServlet; @SuppressWarnings("serial") public class CrunchifyExample extends HttpServlet { public void init() throws ServletException { System.out.println("----------"); System.out.println("---------- CrunchifyExample Servlet Initialized successfully ----------"); System.out.println("----------"); } }
Now Clean your project -> Deploy your project to Tomcat -> Start Tomcat. Check your systemout logs and you should see output like this
---------- ---------- CrunchifyExample Servlet Initialized successfully ---------- ----------
Enjoy and Happy Coding..
The post How to Run Java Program Automatically on Tomcat Startup appeared first on Crunchify.