如何在 Apache Tomcat 中初始化 Web 应用程序?

How to initialize a web application in Apache Tomcat?

我使用的是 WebSphere Application Server,它提供了一个平台初始化侦听器,在应用程序启动时调用该侦听器。现在,我正在使用 Apache Tomcat,但还没有找到这样的东西,我想做的是在应用程序开始为请求提供服务之前做一些初始化工作。

Apache 应该怎么做 Tomcat?

您可以使用 ServletContextListener API。请阅读此link. You can go and checkout this tutorial

您应该在此方法中编写自定义应用程序启动代码

@Override
public void contextInitialized(ServletContextEvent arg0) {
    System.out.println("ServletContextListener started");   
}

注意:如果将来需要,移动到另一台服务器时不会有任何问题。

你创建一个 Listener class what implement ServletContextListener 这样的:

package com.vy;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

@WebListener
public class StartStopListener implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        System.out.println("Servlet has been started.");
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        System.out.println("Servlet has been stopped.");
    }

}

像这样将配置信息添加到WEB-INF\web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">

    <listener>
        <listener-class>com.vy.StartStopListener</listener-class>
    </listener>

</web-app>

当运行 Tomcat时,您将在控制台屏幕上看到结果:

Servlet has been started.

参考:http://docs.oracle.com/javaee/7/api/javax/servlet/ServletContextListener.html