Servlet监听器总结
何为监听器?顾名思义就是监听行为。在Web系统中,所谓的监听器就是应用监听事件来监听请求的行为而创建的一组类。HttpServletRequest、HttpSesion、ServletContxet对象在Web容器中遵守创建、运行、销毁这样的生命周期。当进行相关的监听配置后,Web容器就会调用监听器上的方法,进行对应的事件处理,从而了解运行的情况。各监听接口和事件类如下表:
注意:使用监听器需要实现相应的监听接口。在触发监听事件时,应用服务器会自动调用监听方法。不需要关心服务器如何调用,只需要实现这些方法就行。
ServletContext事件监听器
- ServletContextListener
ServletContextListener被称为“ServletContextListener生命周期监听器”,可以用来监听Web程序初始化和结束时响应的动作事件。其中ServletContextListener接口的类提供了两个监听方法:
- Public void contextInitialized(ServletContextEvent sce):该方法用于通知监听器,已经加载Web应用。
- Public void contextDestroyed(ServletContextEvent sce):该方法用于通知监听器,Web应用即将关闭。
- ServletContextAttributeListener
ServletContextAttributeListener被称为“ServletContext属性监听器”,可以用来监听Application属性的添加、移除或者替换时响应的动作事件。其中ServletContextAttributeListener接口提供了三个监听方法:
- Public void attributeAdded(ServletContextAttributeEvent scab):该方法用于通知监听器,有对象或者属性从Application中添加。
- Public void attributeRemoved(ServletContextAttributeEvent scab):该方法用于通知监听器,有对象或者属性从Application中移除。
- Public void attributeReplaced(ServletContextAttributeEvent scab):该方法用于通知监听器,有对象或者属性从Application中更改。
HttpSession事件监听器
- HttpSessionListener
HttpSessionListener被称为“HttpSessionListener生命周期监听器”,可以用来监听HttpSession对象初始化和结束时响应的动作事件。其中HttpSessionListener接口的类提供了两个监听方法:
- Public void sessionCreated(HttpSessionEvent se):该方法用于通知监听器,产生了新的会话。
- Public void sessionDestroyed(HttpSessionEvent se):该方法用于通知监听器,即将销毁会话。
- ServletContextAttributeListener
HttpSessionAttributeListener被称为“HttpSession属性监听器”,可以用来监听HttpSession属性的添加、移除或者替换时响应的动作事件。其中HttpSessionAttributeListener接口提供了三个监听方法:
- Public void attributeAdded(HttpSessionBindingEvent se):该方法用于通知监听器,有对象或者属性从Session中添加。
- Public void attributeRemoved(HttpSessionBindingEvent se):该方法用于通知监听器,有对象或者属性从Session中移除。
- Public void attributeReplaced(HttpSessionBindingEvent se):该方法用于通知监听器,有对象或者属性从Session中更改。
HttpServletRequest事件监听器
- ServletRequestListener
ServletRequestListener被称为“ServletRequestListener生命周期监听器”,可以用来监听Web程序初始化和结束时响应的动作事件。其中ServletRequestListener接口的类提供了两个监听方法:
- Public void requestInitialized(ServletRequestEvent se):该方法用于通知监听器,产生了新的request对象
- Public void requestDestroyed(ServletRequestEvent se):该方法用于通知监听器,即将销毁一个reuqest对象。
- ServletRequestAttributeListener
ServletRequestAttributeListener被称为“Request属性监听器”,可以用来监听Request属性的添加、移除或者替换时响应的动作事件。其中ServletRequestAttributeListener接口提供了三个监听方法:
- Public void attributeAdded(ServletRequestAttributeEvent se):该方法用于通知监听器,有对象或者属性从Request中添加。
- Public void attributeRemoved(ServletRequestAttributeEvent se):该方法用于通知监听器,有对象或者属性从Request中移除。
- Public void attributeReplaced(ServletRequestAttributeEvent se):该方法用于通知监听器,有对象或者属性从Request中更改。
那么,我们该如何在Web项目中创建一个监听类呢?步骤如下:
一、 首先,编写一个监听类并实现ServletContextListener接口:
二、 进行相关的配置如下:
- 通过web.xml来进行配置:
com.gx.listener.ContextListener
- 通过注入的方式注入监听器(注意:该方式需要web.xml 3.0版本):
@WebListener