Servlet 規範定義 8 個 Listener 接口、6 個 Event 類,對應 Web 應用的三大作用域(Context、Session、Request)的創建銷毀與屬性變更事件。
| Listener 接口 | 核心方法 | 事件類 | 觸發場景 |
|---|---|---|---|
ServletContextListener | contextInitialized()contextDestroyed() | ServletContextEvent | Web 應用啟動/停止、重新部署 |
ServletContextAttributeListener | attributeAdded()attributeReplaced()attributeRemoved() | ServletContextAttributeEvent | Application 域屬性增/改/刪 |
HttpSessionListener | sessionCreated()sessionDestroyed() | HttpSessionEvent | Session 創建/銷毀(超時、invalidate) |
HttpSessionAttributeListener | attributeAdded()attributeReplaced()attributeRemoved() | HttpSessionBindingEvent | Session 域屬性增/改/刪 |
ServletRequestListener | requestInitialized()requestDestroyed() | ServletRequestEvent | Request 對象創建/銷毀(每次請求) |
ServletRequestAttributeListener | attributeAdded()attributeReplaced()attributeRemoved() | ServletRequestAttributeEvent | Request 域屬性增/改/刪 |
HttpSessionBindingListener | valueBound()valueUnbound() | HttpSessionBindingEvent | 實現該接口的對象被放入/移出 Session 時自動回調,**無需在 web.xml 註冊** |
HttpSessionActivationListener | sessionDidActivate()sessionWillPassivate() | HttpSessionEvent | Session 鈍化/活化(分布式/集群環境序列化持久化),**無需在 web.xml 註冊** |
除 HttpSessionBindingListener 和 HttpSessionActivationListener 外,其餘 6 個需在 web.xml 註冊:
<listener>
<listener-class>com.example.CustomServletContextListener</listener-class>
</listener>
Servlet 3.0+ 可用 @WebListener 註解替代 XML 配置。
contextInitializedrequestInitialized → 處理業務 → requestDestroyedsessionCreated → 屬性操作觸發 Attribute 事件 → 銷毀 → sessionDestroyedcontextDestroyed掌握八大監聽器,即掌握了 Web 應用全生命周期的切面編程能力。