Servlet的llistener接口详解

来源:互联网 发布:mac pro apple care 编辑:程序博客网 时间:2024/05/20 15:10

总体上说 servlet 中有主要有 3 类事件既: Servlet 上下文事件、会话事件与请求事件总共有 8 个 listener( 部分类容转载于 http://ritaleo.javaeye.com/blog/48751 ) 接口,我们在 web.xml 中注册时对应上自己对相应接口的实现类即可:

Servlet 中的 Listener 和 Event:

1.         在 JSP 2.0/Servlet 2.4 中,共有八个 Listener 接口,六个 Event 类别。 
ServletContextListener 接口 
[ 接口方法 ] contextInitialized() 与 contextDestroyed() 
[ 接收事件 ] ServletContextEvent 
[ 触发场景 ] 在 Container 加载 Web 应用程序时(例如启动 Container 之后),会呼叫 contextInitialized() ,而当容器移除 Web 应用程序时,会呼叫 contextDestroyed () 方法。

2.         ServletContextAttributeListener 
[ 接口方法 ] attributeAdded() 、 attributeReplaced() 、 attributeRemoved() 
[ 接收事件 ] ServletContextAttributeEvent 
[ 触发场景 ] 若有对象加入为 application ( ServletContext )对象的属性,则会呼叫 attributeAdded() ,同理在置换属性与移除属性时,会分别呼叫 attributeReplaced() 、 attributeRemoved() 。

3.         HttpSessionListener 
[ 接口方法 ] sessionCreated() 与 sessionDestroyed () 
[ 接收事件 ] HttpSessionEvent 
[ 触发场景 ] 在 session ( HttpSession )对象建立或被消灭时,会分别呼叫这两个方法。

4.         HttpSessionAttributeListener 
[ 接口方法 ] attributeAdded() 、 attributeReplaced() 、 attributeRemoved() 
[ 接收事件 ] HttpSessionBindingEvent 
[ 触发场景 ] 若有对象加入为 session ( HttpSession )对象的属性,则会呼叫 attributeAdded() ,同理在置换属性与移除属性时,会分别呼叫 attributeReplaced() 、 attributeRemoved() 。

5.         HttpSessionActivationListener 
[ 接口方法 ] sessionDidActivate() 与 sessionWillPassivate() 
[ 接收事件 ] HttpSessionEvent 
[ 触发场景 ] Activate 与 Passivate 是用于置换对象的动作,当 session 对象为了资源利用或负载平衡等原因而必须暂时储存至硬盘或其它储存器时(透 过对象序列化),所作的动作称之为 Passivate ,而硬盘或储存器上的session 对象重新加载 JVM 时所采的动作称之为 Activate ,所以容 易理解的, sessionDidActivate() 与sessionWillPassivate() 分别于 Activeate 后与将 Passivate 前呼叫。

6.         ServletRequestListener 
[ 接口方法 ] requestInitialized() 与 requestDestroyed() 
[ 接收事件 ] RequestEvent 
[ 触发场景 ] 在 request ( HttpServletRequest )对象建立或被消灭时,会分别呼叫这两个方法。

7.         ServletRequestAttributeListener 
[ 接口方法 ] attributeAdded() 、 attributeReplaced() 、 attributeRemoved() 
[ 接收事件 ] HttpSessionBindingEvent 
[ 触发场景 ] 若有对象加入为 request ( HttpServletRequest )对象的属性,则会呼叫 attributeAdded() ,同理在置换属性与移除属性时,会分别呼叫 attributeReplaced() 、 attributeRemoved() 。

8.         HttpSessionBindingListener 
[ 接口方法 ] valueBound() 与 valueUnbound() 
[ 接收事件 ] HttpSessionBindingEvent 
[ 触发场景 ] 实现 HttpSessionBindingListener 接口的类别,其实例如果被加入至 session ( HttpSession )对象的属性中,则会 呼叫 valueBound() ,如果被从 session ( HttpSession )对象的属性中移除,则会呼叫valueUnbound() ,实现 HttpSessionBindingListener 接口的类别不需在 web.xml 中设定。

 

具体使用方法:在 web.xml 中添加如下语句:

< listener >  
< listener -class > com.servlet .listener .YouAchieveListener  < /listener -class >

< /listener >

其中 YouAchieveListener   为你实现的某个 Listener 接口的实现类 com.servlet .listener . 为你的包名。

0 0
原创粉丝点击