美文网首页JAVA
Listener监听器讲解

Listener监听器讲解

作者: WebGiser | 来源:发表于2018-05-07 17:10 被阅读1次

    1、监听器的启动优先级顺序:监听器 > 过滤器 > servlet

    2、根据监听域划分监听器:

    (1)监听ServletContext,实现ServletContextListener接口。

        两个事件处理方法:contextInitialized、contextDestroyed。
    
        主要用途:定时器、全局属性对象
    

    (2)监听HttpSession,实现HttpSessionListener接口。

      两个事件处理方法:sessionCreated、sessionDestroyed。
    
      主要用途:统计在线人数、记录访问日志
    

    (3)监听ServletRequest,实现ServletRequestListener接口。

        两个事件处理方法:requestInitialized、requestDestroyed。
    
        主要用途:读取参数、记录访问历史
    

    3、监听域对象中的属性的增加和删除的事件监听器:

    (1)监听ServletContext属性变化,实现 ServletContextAttributeListener接口。

      3个事件处理方法:attributeAdded、attributeRemoved、  attributeReplaced。
    

    (2)监听HttpSession属性变化,实现HttpSessionAttrubuteListener 接口。

      3个事件处理方法:attributeAdded、attributeRemoved、  attributeReplaced。
    

    (3)监听ServletRequest属性变化,实现 ServletRequestAttributeListener接口。

      3个事件处理方法:attributeAdded、attributeRemoved、  attributeReplaced。
    

    4、监听器在Web.xml中的配置:

    image

    5、绑定到HttpSession域中的某个对象状态的监听:

    实现HttpSessionBindingListener、HttpSessionActivationListener、 Serialized接口。

    主要处理方法:valueBound、valueUnbound

    Session正常存储在服务器内存中。Session钝化机制本质就在于把服务器中不经常使用的Session对象暂时序列化到系统文件或数据库系统中,当被使用时,反序列化到内存中,整个过程由服务器自动完成。

    钝化:将Session对象持久到系统文件上。

    活化:将Session对象从系统文件恢复到内存中。

    服务器关闭后,把当前Session中的监听对象钝化 到 tomcat的work目录下,下次启动后可以活化该文件。

    6、案例:监听在线用户的数量、ip等信息

    (1)监听HttpSession:

    image

    (2)监听ServletRequest:

    [图片上传中...(image-24b5ed-1525684433032-4)]

    (3)web.xml配置:

    image

    (4)用户信息类(略去get、set方法)

    image

    (5)SessionUtil类:

    image

    (6)index.jsp展示用户信息:

    [图片上传中...(image-8d7378-1525684433032-0)]

    相关文章

      网友评论

        本文标题:Listener监听器讲解

        本文链接:https://www.haomeiwen.com/subject/uxevrftx.html