Servlet監(jiān)聽器的接口
Web應(yīng)用服務(wù)器會產(chǎn)生各種事件,如Web容器啟動事件、session過期事件、請求到達(dá)事件等等。我們已經(jīng)在《JBuilder 2005實(shí)戰(zhàn)JSP開發(fā)》中闡述了這些事件的接口,事件處理方法使程序?qū)eb應(yīng)用服務(wù)器的控制能力大為提高。
在這一節(jié)里,我們監(jiān)聽Web容器啟動關(guān)閉的事件,在事件發(fā)生時(shí)記錄Web應(yīng)用程序啟動和關(guān)閉的系統(tǒng)日志,以便系統(tǒng)管理員通過這個(gè)日志查看Web應(yīng)用程序的啟動和關(guān)閉情況。日志以Excel文件格式保存在D:/serverLog的目錄下。當(dāng)?shù)卿洺晒螅脩艨梢詫⑦@份日志以附件的形式下載下來,下載Excel日志文件的功能將在本專題的最后一節(jié)實(shí)現(xiàn)。下面我們來創(chuàng)建這個(gè)記錄系統(tǒng)日志的Servlet監(jiān)聽器。
1.啟動創(chuàng)建Servlet監(jiān)聽器的向?qū)?/P>
通過File->New...->W(wǎng)eb->雙擊Listener Servlet圖標(biāo)啟動創(chuàng)建Servlet監(jiān)聽器的向?qū)?/P>
這一步和創(chuàng)建標(biāo)準(zhǔn)Servlet類似,我們指定監(jiān)聽器的類名為:SrvStart Listener,包名為bookstore.servlet,按Next到下一步。
2.指定Servlet監(jiān)聽器實(shí)現(xiàn)的事件接口
因?yàn)閃eb容器的啟動和關(guān)閉事件是ServletContextListener接口定義的,所以我們選擇這個(gè)接口,按Finish創(chuàng)建這個(gè)監(jiān)聽器。
打開向?qū)?chuàng)建的SrvStar tListener.java,并錄入下面粗體的代碼:
- package bookstore.servlet;
- …
- import java.io.*;
- import java.util.*;
- import java.text.SimpleDateFormat;
- public class SrvStartListener
- extends HttpServlet implements ServletContextListener
- {
- public void contextInitialized(ServletContextEvent sce)
- {
- GregorianCalendar cal = new GregorianCalendar();
- int year = cal.get(Calendar.YEAR);//得到當(dāng)前年份
- int month = cal.get(Calendar.MONTH)+1;//得到當(dāng)前月份
- File file = new File("D:\\serverLog\\log_"+year+"_"+month+".xls");
- FileWriter fw = null;
- try
- {
- //如果文件存在,日志追加到文件末尾,否則創(chuàng)建新的文件
- fw = new FileWriter(file,true);
- SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
- String starttime = sdf.format(new Date());
- fw.write("于"+starttime+"啟動Web容器\n");
- } catch (IOException ex)
- {
- ex.printStackTrace();
- } finally
- {
- try
- {
- if (fw != null)
- {
- fw.close();
- }
- } catch (IOException ex1)
- {
- ex1.printStackTrace();
- }
- }
- }
- …
- }
【編輯推薦】