java ee监听器编程,java EE开发之Servlet第四课:监听器(Listener)
1.什么是Listener
監聽器就像老板的秘書,那個秘書就是活的監聽器,時時監聽著老板,當老板發生一些事情的時候,秘書就會有相應的措施。比如老板口渴了,秘書就會去端茶;比如老板要提提神,秘書就會泡一杯咖啡等。
2.介紹java的幾種常用的監聽器
(1)實現ServletRequestListener接口,監聽request(需要在web.xml中配置)
/**
* 當request對象被銷毀的時候,容器就會自動去
* 調用這個監聽器的requestDestroyed,產生一個事件對象ServletRequestEvent
*/
public void requestDestroyed(ServletRequestEvent sre) {
System.out.println("request被銷毀");
}
/**
* 當request對象被創建的時候,容器就會自動去
* 調用這個監聽器的requestInitialized,產生一個事件對象ServletRequestEvent*/
public void requestInitialized(ServletRequestEvent sre) {
System.out.println("request被創建");
}
配置:
com.accp.RequestListener
(2)實現HttpSessionListener接口,監聽session (需要在web.xml中配置)
/**
* 當session被創建的時候被調用,產生一個事件對象HttpSessionEvent*/
public void sessionCreated(HttpSessionEvent se) {? }
/**
* 當session被銷毀的時候被調用,產生一個事件對象HttpSessionEvent */
public void sessionCreated(HttpSessionEvent se) {? }
配置:
com.accp.SessiontListener
(3)實現ServletContextListener接口,監聽ServletContext(需要在web.xml中配置)
/**
* 當ServletContext被銷毀的時候,容器就會自動去
* 調用這個監聽器的contextDestroyed,產生一個事件對象ServletContextEvent
*/
public void contextDestroyed(ServletContextEvent sce) {? }
/**
* 當ServletContext被創建的時候,容器就會自動去
* 調用這個監聽器的contextDestroyed,產生一個事件對象ServletContextEvent*/
public void contextInitialized(ServletContextEvent sce) {? }
配置:
com.accp.ContextListener
(4)實現SessionBindingListener接口,監聽Session設值和取值(不需要在web.xml中配置)
/**
* 當向Session里面設值的時候,容器調用此方法,生產一個事件對象? */
public void valueBound(HttpSessionBindingEvent event) { ? }
/**
* 當向Session里面移除值的時候,容器調用此方法,生產一個事件對象? */
public void valueUnbound(HttpSessionBindingEvent event) {? }
哪個類的對象需要監聽,就讓那個類實現該接口
3.應用
應用一
使用 ServletRequestListener ,HttpSessionListener , ServletContextListener
統計訪問量,在線人數,請求次數
應用二
使用SessionBindingListener做購物車:
HttpSessionBindingListener只監聽制定的session
HttpSessionListener:監聽處理所有的session
總結
以上是生活随笔為你收集整理的java ee监听器编程,java EE开发之Servlet第四课:监听器(Listener)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 斑秃是什么原因造成的
- 下一篇: 读取oracle bfile字段,ORA