天天看點

java ee監聽器程式設計,java EE開發之Servlet第四課:監聽器(Listener)

1.什麼是Listener

監聽器就像老闆的秘書,那個秘書就是活的監聽器,時時監聽着老闆,當老闆發生一些事情的時候,秘書就會有相應的措施。比如老闆口渴了,秘書就會去端茶;比如老闆要提提神,秘書就會泡一杯咖啡等。

2.介紹java的幾種常用的監聽器

(1)實作ServletRequestListener接口,監聽request(需要在web.xml中配置)

public void requestDestroyed(ServletRequestEvent sre) {

System.out.println("request被銷毀");

}

public void requestInitialized(ServletRequestEvent sre) {

System.out.println("request被建立");

}

配置:

com.accp.RequestListener

(2)實作HttpSessionListener接口,監聽session (需要在web.xml中配置)

public void sessionCreated(HttpSessionEvent se) {  }

public void sessionCreated(HttpSessionEvent se) {  }

配置:

com.accp.SessiontListener

(3)實作ServletContextListener接口,監聽ServletContext(需要在web.xml中配置)

public void contextDestroyed(ServletContextEvent sce) {  }

public void contextInitialized(ServletContextEvent sce) {  }

配置:

com.accp.ContextListener

(4)實作SessionBindingListener接口,監聽Session設值和取值(不需要在web.xml中配置)

public void valueBound(HttpSessionBindingEvent event) {   }

public void valueUnbound(HttpSessionBindingEvent event) {  }

哪個類的對象需要監聽,就讓那個類實作該接口

3.應用

應用一

使用 ServletRequestListener ,HttpSessionListener , ServletContextListener

統計通路量,線上人數,請求次數

應用二

使用SessionBindingListener做購物車:

HttpSessionBindingListener隻監聽制定的session

HttpSessionListener:監聽處理所有的session