【问题标题】:How to initialize a web application in Apache Tomcat?如何在 Apache Tomcat 中初始化 Web 应用程序?
【发布时间】:2015-02-03 14:38:09
【问题描述】:

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

Apache Tomcat 应该怎么做?

【问题讨论】:

  • 您是否在使用任何框架,例如 SpringMVC、Struts 2 或 PlayFramework?如果是这样,可能存在比ServletContextListener 更自然的特定于框架的答案。但如果这只是一个 Java/Servlet 应用程序,那么给出的答案就是这样做的方法。
  • 不,我没有使用任何。感谢您的帮助。

标签: java tomcat servlets


【解决方案1】:

你创建一个Listener 类,像这样实现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

【讨论】:

  • 使用@WebListener注解时无需在web.xml中配置
【解决方案2】:

您可以使用ServletContextListener API。请阅读此link。你可以去看看这个tutorial

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

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

注意:如果将来需要,移动到其他服务器时不会出现任何问题。

【讨论】:

    猜你喜欢
    • 2018-12-15
    • 2012-05-03
    • 1970-01-01
    • 2013-07-06
    • 2013-12-29
    • 2013-06-16
    • 1970-01-01
    • 2013-10-10
    • 1970-01-01
    相关资源
    最近更新 更多