如何在 Apache Tomcat 中初始化 Web 应用程序? [英] How to initialize a web application in Apache Tomcat?

查看:29
本文介绍了如何在 Apache Tomcat 中初始化 Web 应用程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I was using WebSphere Application Server, and it gives a platform initialization listener which is invoked when an app gets started. Now, I am using Apache Tomcat, but have not found such stuff, and what I'm trying to do is do some initialization work before the application begins to serve requests.

我应该如何通过 Apache Tomcat 做到这一点?

How should I do it by Apache Tomcat?

推荐答案

你创建一个 Listener 类来实现 ServletContextListener 像这样:

You create a Listener class what implement ServletContextListener like this:

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 中,如下所示:

Add configuration information to WEB-INF\web.xml like this:

<?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时,您将在控制台屏幕上看到结果:

When run Tomcat, You will see result at console screen:

Servlet has been started.

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

这篇关于如何在 Apache Tomcat 中初始化 Web 应用程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆