温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Servlet中的Listener接口有哪些

发布时间:2021-12-21 10:14:17 来源:亿速云 阅读:92 作者:iii 栏目:编程语言

这篇文章主要讲解了“Servlet中的Listener接口有哪些”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“Servlet中的Listener接口有哪些”吧!

/Servlet 中的事件处理写过AWT或Swing程序的人一定对桌面程序的事件处理机制印象深刻:通过实现Listener接口的类可以在特定事件(Event)发生时,呼叫特定的方法来对事件进行响应。

其实我们在编写JSP/Servle程序时,也有类似的事件处理机制,所不同的是在JSP/Servlet中是在web.xml中注册Listener,由Container在特定事件发生时呼叫特定的实现Listener的类。

1. Servlet中的Listener和Event:

在JSP 2.0/Servlet 2.4中,共有八个Listener接口,六个Event类别。

l ServletContextListener

[接口方法] contextInitialized()与 contextDestroyed()

[接收事件] ServletContextEvent

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

l ServletContextAttributeListener

[接口方法] attributeAdded()、 attributeReplaced()、attributeRemoved()

[接收事件] ServletContextAttributeEvent

[触发场景] 若有对象加入为application(ServletContext)对象的属性,则会呼叫attributeAdded(),同理在置换属性与移除属性时,会分别呼叫attributeReplaced()、attributeRemoved()。

l HttpSessionListener

[接口方法] sessionCreated()与sessionDestroyed ()

[接收事件] HttpSessionEvent

[触发场景] 在session(HttpSession)对象建立或被消灭时,会分别呼叫这两个方法。

l HttpSessionAttributeListener

[接口方法] attributeAdded()、 attributeReplaced()、attributeRemoved()

[接收事件] HttpSessionBindingEvent

[触发场景] 若有对象加入为session(HttpSession)对象的属性,则会呼叫attributeAdded(),同理在置换属性与移除属性时,会分别呼叫attributeReplaced()、 attributeRemoved()。

l ServletRequestListener

[接口方法] requestInitialized()与 requestDestroyed()

[接收事件] RequestEvent

[触发场景] 在request(HttpServletRequest)对象建立或被消灭时,会分别呼叫这两个方法。

l ServletRequestAttributeListener

[接口方法] attributeAdded()、 attributeReplaced()、attributeRemoved()

[接收事件] HttpSessionBindingEvent

[触发场景] 若有对象加入为request(HttpServletRequest)对象的属性,则会呼叫attributeAdded(),同理在置换属性与移除属性时,会分别呼叫attributeReplaced()、 attributeRemoved()。

l HttpSessionBindingListener

[接口方法] valueBound()与valueUnbound()

[接收事件] HttpSessionBindingEvent

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

l HttpSessionActivationListener

[接口方法] sessionDidActivate()与 sessionWillPassivate()

[接收事件] HttpSessionEvent

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

2. 注册监听器

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

<listener>  <listener-class>  demo.servlet.listener.CustomServletContextListener   listener-class>  listener>

感谢各位的阅读,以上就是“Servlet中的Listener接口有哪些”的内容了,经过本文的学习后,相信大家对Servlet中的Listener接口有哪些这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是亿速云,小编将为大家推送更多相关知识点的文章,欢迎关注!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI