转-JavaWeb三大组件之Listener监听器

时间:2023-03-08 16:21:53
转-JavaWeb三大组件之Listener监听器

JavaWeb三大组件之Listener监听器
一、概述
1,它是一个接口,内容由我们来实现

2,它需要注册,例如注册在按钮上

3,监听器中的方法,会在特殊事件发生时被调用

二、JavaWeb中的监听器
1,事件源

Ø  ServletContext

生命周期监听:ServletContextListener,它有两个方法,一个在出生时调用,一个在死亡时调用;

(1)  void contextInitialized(ServletContextEvent sce):创建SErvletcontext时

(2)  void contextDestroyed(ServletContextEvent sce):销毁Servletcontext时

属性监听:ServletContextAttributeListener,它有三个方法,一个在添加属性时调用,一个在替换属性时调用,最后一个是在移除属性时调用。

(1)  void attributeAdded(ServletContextAttributeEvent event):添加属性时;

(2)  void attributeReplaced(ServletContextAttributeEvent event):替换属性时;

(3)  void attributeRemoved(ServletContextAttributeEvent event):移除属性时;

Ø  HttpSession

生命周期监听:HttpSessionListener,它有两个方法,一个在出生时调用,一个在死亡时调用;

(1)  void sessionCreated(HttpSessionEvent se):创建session时

(2)  void sessionDestroyed(HttpSessionEvent se):销毁session时

属性监听:HttpSessioniAttributeListener,它有三个方法,一个在添加属性时调用,一个在替换属性时调用,最后一个是在移除属性时调用。

(1)  void attributeAdded(HttpSessionBindingEvent event):添加属性时;

(2)  void attributeReplaced(HttpSessionBindingEvent event):替换属性时

(3)  void attributeRemoved(HttpSessionBindingEvent event):移除属性时

Ø  ServletRequest

生命周期监听:ServletRequestListener,它有两个方法,一个在出生时调用,一个在死亡时调用;

(1)  void requestInitialized(ServletRequestEvent sre):创建request时

(2)  void requestDestroyed(ServletRequestEvent sre):销毁request时

属性监听:ServletRequestAttributeListener,它有三个方法,一个在添加属性时调用,一个在替换属性时调用,最后一个是在移除属性时调用。

(1)  void attributeAdded(ServletRequestAttributeEvent srae):添加属性时

(2)  void attributeReplaced(ServletRequestAttributeEvent srae):替换属性时

(3)  void attributeRemoved(ServletRequestAttributeEvent srae):移除属性时

2,JavaWeb中完成编写监听器
(1)写一个监听器类:要求必须去实现某个监听器接口

(2)注册,是在web.xml中配置来完成注册;

3,事件对象

Ø  ServletContextEvent:ServletContext getServletContext()

Ø  HttpSessionEvent:HttpSession getSession()

Ø  ServletRequest:

(1)     ServletContext  getServletContext();

(2)     ServletReques  getServletRequest();

Ø  ServletContextAttributeEvent:

(1)     ServletContext  getServletContext();

(2)     String  getName():获取属性名

(3)     Object  getValue():获取属性值

Ø  HttpSessionBindingEvent:略

Ø  ServletRequestAttributeEvent :略

4,感知监听

1,它用来添加到JavaBean上,而不是添加到三大域上

2,这两个监听器都不需要再web.xml中注册

HttpSessionBindingListener:添加到javabean上,javabean就知道自己是否添加到session中了。

HttpSessionActivationListener监听器与HttpSessionBindingListener监听器相似,都是感知型的监听器,例如让Person类实现了HttpSessionActivationListener监听器接口,并把Person对象添加到了session中后,当Tomcat钝化session时,同时也会钝化session中的Person对象,这时Person对象就会感知到自己被钝化了,其实就是调用Person对象的sessionWillPassivate()方法。当用户再次使用session时,Tomcat会活化session,这时Person会感知到自己被活化,其实就是调用Person对象的sessionDidActivate()方法。
---------------------
作者:职业炮灰
来源:CSDN
原文:https://blog.csdn.net/king_cannon_fodder/article/details/79894304
版权声明:本文为博主原创文章,转载请附上博文链接!