JSP/Servlet Listener 总结

1. Listener介绍

Servlet API 提供了大量监听Web应用的内部时间,允许当Web内部事件发生时,回调事件监听器内的方法。

使用Listener的步骤:

(1)定义Listener实现类

(2)定义Annotation或者配置web.xml


2.常用Web事件监听接口:

共有八个Listener接口,六个Event类别。

(1)ServletContextListener

[接口方法] contextInitialized() contextDestroyed() 
[接收事件] ServletContextEvent 
[触发场景Container加载Web应用程序时(例如启动 Container之后),会呼叫contextInitialized(),而当容器移除Web应用程序时,会呼叫contextDestroyed ()方法。 

(2)ServletContextAttributeListener

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

(3)HttpSessionListener 

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

(4)HttpSessionAttributeListener 

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

(5)ServletRequestListener 

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

(6)ServletRequestAttributeListener 

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

(7)HttpSessionBindingListener 

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

(8)HttpSessionActivationListener 

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


3注册监听器

除了HttpSessionBindingListenerHttpSessionActivationListener,必须在web.xml中向容器注册,容器才会在对应的事件发生时呼叫对应的类别,如: 


分享到:

发表评论

昵称

难的是和自己保持联系~