1. 程式人生 > >servlet session listener

servlet session listener

servlet listener

HttpSessionListener-創建與銷毀

//@WebListener servlet3.0支持註解
public class HttpSessionListenerDemo implements HttpSessionListener{

    @Override
    public void sessionCreated(HttpSessionEvent httpSessionEvent) {
        HttpSession session = httpSessionEvent.getSession();
        ServletContext servletContext = session.getServletContext();
        // undo
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
        // undo
    }
}

HttpSessionActivationListener-頓化與激活

//@WebListener servlet3.0支持註解
public class HttpSessionActivationListenerDemo implements HttpSessionActivationListener {

    @Override
    public void sessionWillPassivate(HttpSessionEvent httpSessionEvent) {

    }

    @Override
    public void sessionDidActivate(HttpSessionEvent httpSessionEvent) {

    }
}

HttpSessionAttributeListener-屬性值變化

//@WebListener servlet3.0支持註解
public class HttpSessionAttributeListenerDemo implements HttpSessionAttributeListener {
    @Override
    public void attributeAdded(HttpSessionBindingEvent httpSessionBindingEvent) {

    }

    @Override
    public void attributeRemoved(HttpSessionBindingEvent httpSessionBindingEvent) {

    }

    @Override
    public void attributeReplaced(HttpSessionBindingEvent httpSessionBindingEvent) {

    }
}

HttpSessionBindingListener-屬性值刪除或增加

//@WebListener servlet3.0支持註解
public class HttpSessionBindingListenerDemo implements HttpSessionBindingListener {
    @Override
    public void valueBound(HttpSessionBindingEvent httpSessionBindingEvent) {

    }

    @Override
    public void valueUnbound(HttpSessionBindingEvent httpSessionBindingEvent) {

    }
}

設計架構
監聽器的設計模式是觀察者模式。
事件源:HttpSession
事件:EventObject的子類,如:HttpSessionEvent和HttpSessionBindingEvent
事件監聽器:EventListener的子類。

被觀察者是servlet容器。觀察者則是我們寫的listener.通常在自已實現的listener中都會引入實際的觀察者,來處理事件。

說明:web.xml的加載順序是:【Context-Param】->【Listener】->【Filter】->【Servlet】,而同個類型之間的實際程序調用的時候的順序是根據對應的Mapping的順序進行調用。

servlet session listener