有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在启动tomcat后执行某些操作

我在ApacheTomcat服务器中部署了web应用程序,在部署主web应用程序之后,我需要启动另一个控制台应用程序(socket服务器)。此socket服务器与主应用程序位于同一WAR文件中,并且可以访问所有bean和web应用程序类。
我需要在使用部署的web应用程序启动tomcat之后启动它(而不是在打开应用程序的索引页或其他内容之后)
我该怎么做


共 (2) 个答案

  1. # 1 楼答案

    使用ServletContextListener,您可以在web中配置它。xml

    当web应用程序启动和停止时,您将获得句柄

  2. # 2 楼答案

    您需要实现ServletContextListner接口

    public class MyServletContextListener implements ServletContextListener {
    
        @Override
        public void contextDestroyed(ServletContextEvent arg0) {
        //Notification that the servlet context is about to be shut down.   
        }
    
        @Override
        public void contextInitialized(ServletContextEvent arg0) {
        // do all the tasks that you need to perform just after the server starts
    
        //Notification that the web application initialization process is starting
        }
    
    }
    

    并在部署描述符中配置它web.xml

    <listener>
        <listener-class>
            mypackage.MyServletContextListener
        </listener-class>
    </listener>