如何在Tomcat中初始化Web应用程序 [英] How to initialize a web application in Tomcat
问题描述
我使用的是websphere应用服务器,它提供了一个平台初始化监听器,当应用程序启动时会调用该监听器。现在,我正在使用Tomcat,但还没有找到这样的东西,而我正在尝试做的是在应用程序开始提供请求之前做一些初始化工作。
I was using websphere application server, and it gives a platform initialization listener which is invoked when an app gets started. Now, I'm using Tomcat, but have not found such stuff, and what I'm trying to do is do some init work before the application begins to serve requests.
Tomcat应该怎么做?
How should I do it by Tomcat?
推荐答案
你创建一个监听器
class什么实现 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
这篇关于如何在Tomcat中初始化Web应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!