我对Tomcat上下文侦听器有疑问。 我想做什么: 当tomcat启动时启动一个线程将基本上执行一些后台数据库操作。 我已经实现了一个ContextLstener类,在web.xml中设置它并实现了一个简单的Thread-Class。
我的问题是,Tomcat启动此线程两次,有时甚至是3次,我不明白为什么。 是的,我是Tomcat和Servlets的新手,是的,我有搜索stackoverflow的解决方案,但无法找到任何东西。
继承我的代码: 的ServletContextListener:
public class EventToUserServletContextListener implements ServletContextListener {
private DatabaseContextThread thread = null;
@Override
public void contextInitialized(ServletContextEvent sce) {
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
if ((thread == null) || (!thread.isAlive())) {
System.out.println("STARTING CONTEXT THREAD");
this.thread = new DatabaseContextThread();
this.thread.start();
}
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
try {
System.out.println("STOPING CONTEXT THREAD");
thread.doShutdown();
thread.interrupt();
} catch (Exception ex) {
System.out.println("Error Stoping Thread: " + ex.getMessage());
}
}
}
线程类
public class DatabaseContextThread extends Thread {
@Override
public void run() {
while (true) {
try {
//TODO Implement Context
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
System.out.println(date + " THIS IS THREAD!!! " + this.toString());
sleep(20000);
} catch (InterruptedException ex) {
Logger.getLogger(DatabaseContextThread.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public void doShutdown() {
}
}
的web.xml
<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">
<servlet>
<servlet-name>Jersey RESTfull Server Thesis</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>de.mk</param-value>
</init-param>
<load-on-startup>10</load-on-startup>
</servlet>
<listener>
<listener-class>de.mk.dao.listener.EventToUserServletContextListener</listener-class>
</listener>
<servlet-mapping>
<servlet-name>Jersey RESTfull Server Thesis</servlet-name>
<url-pattern>/webapi/*</url-pattern>
</servlet-mapping>
</web-app>
Sat Apr 12 11:26:27 CEST 2014这是线索!螺纹[线程6,5,主]
Sat Apr 12 11:26:29 CEST 2014这是线索!螺纹[线程8,5,主]
星期六4月12日11:26:47 CEST 2014这是线索!螺纹[线程6,5,主]
Sat Apr 12 11:26:49 CEST 2014这是线索!螺纹[线程8,5,主]
答案 0 :(得分:0)
检查您定义上下文的次数。将为每个上下文执行上下文侦听器。 如果使用虚拟主机,或者在war(META-INF / context.xml)中定义一个上下文,而在server.xml中定义其他上下文,则可以有多个上下文(不应在此处定义)。