JavaWeb—监听器

监听器简介

什么是监听器?
能监听某个对象的状态变化的组件,监听域对象的变化。
监听器相关的概念

  • 事件源:被监听的对象request,session,servletContext。
  • 监听器:监听事件源的对象 ,8个监听器。
  • 注册监听器:监听器与事件源相绑定
  • 响应行为:监听到事件源变化时,去做什么事情。

监听器划分:
三个监听域对象的创建与销毁:

  • ServletContextListener
  • HttpSessionListener
  • ServletRequestListener
    三个监听域对象当中属性变化:
  • ServletContextAttributeListener
  • HttpSessionAttributeListener
  • ServletRequestAttributeListener

域监听器

  • ServletContext域监听器
  • HttpSessionListener
  • ServletRequestListener
@WebListener()
public class Listener implements ServletContextListener,
        HttpSessionListener, HttpSessionAttributeListener {

    // Public constructor is required by servlet spec
    public Listener() {
    }

    // -------------------------------------------------------
    // ServletContextListener implementation
    // -------------------------------------------------------
    public void contextInitialized(ServletContextEvent sce) {
        System.out.println("contextInitialized");
    }

    public void contextDestroyed(ServletContextEvent sce) {
        System.out.println("contextDestroyed");
    }

    // -------------------------------------------------------
    // HttpSessionListener implementation
    // -------------------------------------------------------
    public void sessionCreated(HttpSessionEvent se) {
        System.out.println("sessionCreated");
    }

    public void sessionDestroyed(HttpSessionEvent se) {
        System.out.println("sessionDestroyed");
    }

    // -------------------------------------------------------
    // HttpSessionAttributeListener implementation
    // -------------------------------------------------------

    public void attributeAdded(HttpSessionBindingEvent sbe) {
      /* This method is called when an attribute 
         is added to a session.
      */
    }

    public void attributeRemoved(HttpSessionBindingEvent sbe) {
      /* This method is called when an attribute
         is removed from a session.
      */
    }

    public void attributeReplaced(HttpSessionBindingEvent sbe) {
      /* This method is invoked when an attribute
         is replaced in a session.
      */
    }
}

web.xml中配置

 <listener>
        <listener-class>org.youyuan.servlet.Listener</listener-class>
    </listener>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值