Every one who is using tomcat and java, face problem of starting program automatically on tomcat startup. To run java program automatically on tomcat startup, need to use Servlet and this Servlet initialized on tomcat startup automatically.
How it will work, we will explain in next phase. Most of small and big web application needs to execute some queries and java program in background, without opening on the web browser and user interaction.
If we want to start scheduler for newsletter which has to send newsletter on everyday in evening, you have to start timer when tomcat started. This timer works in background for waiting to come evening to send newsletter, without opening script on web browser and manual process by user.
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.
<?xml version="1.0" encoding="UTF-8"?> <web-app> <servlet> <servlet-name>ServletInitializer</servlet-name> <servlet-class>com.cron.ServletInitializer</servlet-class> <load-on-startup>1</load-on-startup> </servlet> </web-app>
ServletInitializer.java
package com.cron; import java.io.*; import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletResponse; public class ServletInitializer extends HttpServlet { public void init() throws ServletException { /// Automatically java script can run here System.out.println("************"); System.out.println("*** Servlet Initialized successfully ***.."); System.out.println("***********"); } public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } }
Start tomcat and see output in console mode



Link to Us