<b>Java顶用Servlet容器实现程序监听</b>[Java编程]
本文“<b>Java顶用Servlet容器实现程序监听</b>[Java编程]”是由七道奇为您精心收集,来源于网络转载,文章版权归文章作者所有,本站不对其观点以及内容做任何评价,请读者自行判断,以下是其具体内容:
分两步走:
(1). 实现 javax.servlet.ServletContextListener 接口的两个办法:contextInitialized()和contextDestroyed()
contextInitialized():当Servlet容器启动时会履行
contextDestroyed():当Servlet容器终止时会履行
(2). 在contextInitialized()中加入需求监听的程序,并由 java.util.Timer 的 schedule() 办法来掌握监听程序履行的频率
DEMO(这是我的一个短信答复监听的程序原型,精简了一下)
----------------------------------------------------------------
ReplyListener.java
----------------------------------------------------------------
package com.hanweb.jcms;
import javax.servlet.*;
public class ReplyListener implements ServletContextListener {
private ReplyTimer rt = null;
public void contextInitialized(ServletContextEvent event) {
String status = "[SYS] SMS reply listener start .";
event.getServletContext().log(status);
System.out.println(status);
rt = new ReplyTimer(1);
rt.start();
}
public void contextDestroyed(ServletContextEvent event) {
String status = "[SYS] SMS reply listener stop .";
event.getServletContext().log(status);
System.out.println(status);
if (rt != null) {
rt.stop();
}
}
}
----------------------------------------------------------------
ReplyTimer.java
----------------------------------------------------------------
package com.hanweb.jcms;
import java.util.*;
public class ReplyTimer {
private final Timer timer = new Timer();
private final int min;
public ReplyTimer(int minutes) {
min = minutes;
}
public void start() {
Date date = new Date();
timer.schedule(new ReplyTask(), date, min * 60 * 1000);
}
public void stop() {
timer.cancel();
}
}
----------------------------------------------------------------
ReplyTask.java
----------------------------------------------------------------
package com.hanweb.jcms;
import java.util.*;
public class ReplyTask extends TimerTask {
public void doSomething() {
System.out.println("[SYS] SMS reply listener running ");
}
public void run() {
doSomething();
}
}
将编译好的class文件放入WEB-INF/classes中,最后别忘掉了在Servlet容器中当前WEB利用的web.xml中加入监听语句:
<listener>
<listener-class>com.hanweb.jcms.ReplyListener</listener-class>
</listener>
以上是“<b>Java顶用Servlet容器实现程序监听</b>[Java编程]”的内容,如果你对以上该文章内容感兴趣,你可以看看七道奇为您推荐以下文章:
本文地址: | 与您的QQ/BBS好友分享! |