How to Run Java Program Automatically on Tomcat Startup

如何在启动tomcat时候,自动启动一个jar程序。

觉得这个应该在打包tomcat web服务为一个独立程序的时候应该有点作用。原文博客特别不错。

原文地址:https://crunchify.com/how-to-run-java-program-automatically-on-tomcat-startup/

Apache Tomcat - Crunchify Tips

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?
  • How to Start a service automatically when the tomcat starts

To run java program automatically on tomcat startup, need to use Servletand this Servlet initialized on tomcat startup automatically.

To execute a program, you have to use Servlet and Servlet should define in deployment descriptor web.xml file under WEB-INF folder.

web.xml file contain tags <load-on-startup> and <servlet> tag. Servlet tag keeps 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.

Step-1

Modify Web.xml file with below information. Where CrunchifyServletExample is a class name and crunchify.com.tutorials is a package name.

Modify these values as per your need.

This is my complete web.xml file

Step-2

Step-3

Now Clean your project using Maven or Project Menu -> Clean

Step-4

  • Deploy your project to Tomcat
  • Start Tomcat
  • Check your system out logs and you should see output like this

Enjoy and Happy Coding..


猜你喜欢

转载自blog.csdn.net/zw3413/article/details/79380400
今日推荐