点击这里给我发消息 点击这里给我发消息

Java中用Servlet容器实现程序监听

添加时间:2013-12-7
    相关阅读: WEB 程序

  分两步走:
  
  (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>
咨询热线:020-85648757 85648755 85648616 0755-27912581 客服:020-85648756 0755-27912581 业务传真:020-32579052
广州市网景网络科技有限公司 Copyright◎2003-2008 Veelink.com. All Rights Reserved.
广州商务地址:广东省广州市黄埔大道中203号(海景园区)海景花园C栋501室
= 深圳商务地址:深圳市宝源路华丰宝源大厦606
研发中心:广东广州市天河软件园海景园区 粤ICP备05103322号 工商注册