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