日本综合一区二区|亚洲中文天堂综合|日韩欧美自拍一区|男女精品天堂一区|欧美自拍第6页亚洲成人精品一区|亚洲黄色天堂一区二区成人|超碰91偷拍第一页|日韩av夜夜嗨中文字幕|久久蜜综合视频官网|精美人妻一区二区三区

RELATEED CONSULTING
相關(guān)咨詢
選擇下列產(chǎn)品馬上在線溝通
服務(wù)時(shí)間:8:30-17:00
你可能遇到了下面的問題
關(guān)閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
監(jiān)聽Servlet容器的方法

1.實(shí)現(xiàn) javax.servlet.ServletContextListener 接口的兩個(gè)方法:contextInitialized()和contextDestroyed()

contextInitialized():當(dāng)Servlet容器啟動(dòng)時(shí)會(huì)執(zhí)行
contextDestroyed():當(dāng)Servlet容器停止時(shí)會(huì)執(zhí)行

2.在contextInitialized()中加入需要監(jiān)聽的程序,并由 java.util.Timer 的 schedule() 方法來控制監(jiān)聽程序執(zhí)行的頻率

DEMO(這是我的一個(gè)短信回復(fù)監(jiān)聽的程序原型,精簡了一下)

ReplyListener.java

 
 
 
  1. package com.hanweb.jcms;  
  2.  
  3. import javax.servlet.*;  
  4.  
  5. public class ReplyListener implements ServletContextListener {  
  6. private ReplyTimer rt = null;  
  7. public void contextInitialized(ServletContextEvent event) {  
  8. String status = "[SYS] SMS reply listener start .";  
  9. event.getServletContext().log(status);  
  10. System.out.println(status);  
  11.  
  12. rt = new ReplyTimer(1);  
  13. rt.start();  
  14. }  
  15.  
  16. public void contextDestroyed(ServletContextEvent event) {  
  17. String status = "[SYS] SMS reply listener stop .";  
  18. event.getServletContext().log(status);  
  19. System.out.println(status);  
  20.  
  21. if (rt != null) {  
  22. rt.stop();  
  23. }  
  24. }  

ReplyTimer.java

 
 
 
  1. package com.hanweb.jcms;  
  2.  
  3. import java.util.*;  
  4.  
  5. public class ReplyTimer {  
  6. private final Timer timer = new Timer();  
  7. private final int min;  
  8.  
  9. public ReplyTimer(int minutes) {  
  10. min = minutes;  
  11. }  
  12.  
  13. public void start() {  
  14. Date date = new Date();  
  15. timer.schedule(new ReplyTask(), date, min * 60 * 1000);  
  16. }  
  17.  
  18. public void stop() {  
  19. timer.cancel();  
  20. }  

ReplyTask.java

 
 
 
  1. package com.hanweb.jcms;  
  2.  
  3. import java.util.*;  
  4.  
  5. public class ReplyTask extends TimerTask {  
  6. public void doSomething() {  
  7. System.out.println("[SYS] SMS reply listener running ");  
  8. }  
  9.  
  10. public void run() {  
  11. doSomething();  
  12. }  

將編譯好的class文件放入WEB-INF/classes中,***別忘記了在Servlet容器中當(dāng)前WEB應(yīng)用的web.xml中加入監(jiān)聽語句:

 
 
 
  1.  
  2. com.hanweb.jcms.ReplyListener 
  3.  

【編輯推薦】

  1. 詳解Apache Servlet的安裝
  2. 優(yōu)化Servlet配置為web.xml瘦身
  3. 如何讓XML來配置Servlet
  4. 解決Servlet JSP頁面亂碼問題
  5. Servlet和JSP的安全問題

當(dāng)前名稱:監(jiān)聽Servlet容器的方法
文章源于:http://www.dlmjj.cn/article/cocigej.html