用 servlet 實(shí)現(xiàn)監(jiān)聽器工作需要,對(duì)監(jiān)聽器的實(shí)現(xiàn)做了研究學(xué)習(xí),記錄如下
監(jiān)聽器的種類很多,基本分類如下圖的JB2006的圖式就可以看出來.......暈 無法添加圖片 ???
基本分為 對(duì) context session request 。
基本事件做下面的關(guān)系圖說明
context —— ServletContextListener
—— ServletAttributeContextListener
session —— SessionContextListener
—— SessionAttributeContextListener
request —— RequestContextListener
—— RequestAttributeContextListener
對(duì)于每個(gè)監(jiān)聽器,分別繼承了不同的方法,如下
contextInitialized // servlet 容器被加載的時(shí)候
contextDestroyed // servlet 容器被撤銷的時(shí)候 attributeAdded // 添加 servlet 屬性時(shí)
attributeRemoved // 移除 servlet 屬性時(shí) attributeReplaced // 更新 servlet 屬性時(shí) sessionCreated //略 sessionDestroyed
attributeAdded
attributeRemoved attributeReplaced requestInitialized requestDestroyed attributeAdded
attributeRemoved attributeReplaced 最后,將實(shí)現(xiàn)的類添加到應(yīng)用服務(wù)的 web.xml中:
<listener> <listener-class>類路徑</listener-class> </listener> 通過以上的方法實(shí)現(xiàn),我們實(shí)現(xiàn)了對(duì)服務(wù)器事件內(nèi)容的響應(yīng),但這還不是我們預(yù)期的結(jié)果。
我們的原始需求,要做一個(gè)定時(shí)監(jiān)聽器,在服務(wù)啟動(dòng)的時(shí)候,可以同時(shí)運(yùn)行起來,并且定
時(shí)監(jiān)聽其他服務(wù)器內(nèi)容的更改,在服務(wù)關(guān)掉的時(shí)候,停止監(jiān)聽 。以上只是實(shí)現(xiàn)了監(jiān)聽事件
與服務(wù)事件的響應(yīng),接下來,實(shí)現(xiàn)事件與時(shí)間的相互響應(yīng)。
首先建立一個(gè)服務(wù)與事件的相應(yīng)的應(yīng)用實(shí)現(xiàn)
import java.util.*;
public class appServerEven {
private final Timer timer = new Timer(); // 建立時(shí)間監(jiān)聽對(duì)象 public appServerEven() { } public void start() {
timer.schedule(事件處理類, 開始時(shí)間, 時(shí)間間隔); /**
Date date = new Date(); // 系統(tǒng)當(dāng)前時(shí)間
timer.schedule(new appEven() , date, 分鐘 * 60 * 1000); */
} public void stop() {
timer.cancel(); } } 其次,建立事件與時(shí)間的響應(yīng)事件
import java.util.*;
import java.text.SimpleDateFormat; public class ReplyTask extends TimerTask // 擴(kuò)展實(shí)現(xiàn)TimeTask 時(shí)間任務(wù)
{
public void run() { // 根據(jù)時(shí)間,進(jìn)行的事物處理的 /**
// 輸出當(dāng)前的系統(tǒng)時(shí)間
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String starttime = sdf.format(new Date()); System.out.println(starttime); */
} } 通過將上面的"時(shí)間",修改為具體數(shù)據(jù),我們就實(shí)現(xiàn)了一個(gè)在WEB應(yīng)用服務(wù)啟動(dòng)的時(shí)候自動(dòng)啟動(dòng),
并且,每隔幾分鐘自動(dòng)輸出系統(tǒng)當(dāng)前時(shí)間到界面的監(jiān)聽器.( 完 ) |
|