javaWEB监听器
javaWEB有三大组件,Servlet、Listener、Filter,这篇博客记录一下Listener的使用
1、监听器是一个接口,具体的内容由我们自己来实现,他需要注册,监听器中的方法会在特殊事件发生时被调用。事件有三个组成部分,事件源(相当于由谁触发事件)、事件(触发什么样的事件)、监听器(监控,一但发生什么事就立即执行相对应的方法),javaWEB中的监听器属性要求实现某个监听器接口,并且在web.xml中注册
2、javaWEB中的三大监听器
-
事件源:三大域
> ServletContext
生命周期监听:ServletContextListener,他有两个方法:-
void contextInitialized(ServletContextEvent sce):创建SErvletcontext时
-
void contextDestroyed(ServletContextEvent sce):销毁Servletcontext时
属性监听:有三个方法,第一个是向域中添加属性时调用,第二个是修改属性时调用,第三个是删除属性时调用 -
void attributeAdded(ServletContextAttributeEvent event):添加属性时;
-
void attributeReplaced(ServletContextAttributeEvent event):替换属性时;
-
void attributeRemoved(ServletContextAttributeEvent event):移除属性时;
>HttpSession
生命周期监听:HttpSessionListener,他有两个方法:- void sessionCreated(HttpSessionEvent se):创建session时.
- void sessionDestroyed(HttpSessionEvent se):销毁session时
属性监听
- void attributeAdded(HttpSessionBindingEvent event):添加属性时;
- void attributeReplaced(HttpSessionBindingEvent event):替换属性时
- void attributeRemoved(HttpSessionBindingEvent event):移除属性时
>ServletRequest
生命周期监听:ServletRequestListener,他有两个方法:- void requestInitialized(ServletRequestEvent sre):创建request时
- void requestDestroyed(ServletRequestEvent sre):销毁request时
属性监听:
- void attributeAdded(ServletRequestAttributeEvent srae):添加属性时
- void attributeReplaced(ServletRequestAttributeEvent srae):替换属性时
- void attributeRemoved(ServletRequestAttributeEvent srae):移除属性时
-
参数介绍
1、生命周期方法中的对象
- ServletContextEvent:ServletContext getServletContext();
- HttpSeessionEvent:HttpSession getSession();
- ServletRequestEvent:
- ServletRequest getServletRequest()
- ServletContext getServletContext()
属性监听中的方法
1、ServletContextAttributeEvent
- String getName():获取当前操作的属性名;
- Object getValue():获取当前操作的属性值;
- ServletContext getServletContext():获取ServletContext对象。
2、HttpSessionBindingEvent
- String getName():获取当前操作的属性名;
- Object getValue():获取当前操作的属性值;
- HttpSession getSession():获取当前操作的session对象。
3、ServletRequestAttributeEvent
- String getName():获取当前操作的属性名;
- Object getValue():获取当前操作的属性值;
- ServletContext getServletContext():获取ServletContext对象;
- ServletRequest getServletRequest():获取当前操作的ServletRequest对象。
到此监听的一些方法基本都记录了,接下来用代码演示怎么实现和注册
实现监听器在xml中注册
到这,就可以配置自己的监听器了。