11.servlet里面的监听器

1.启动Web容器,容器会自动识别监听器,并在对应事件触发时调用处理方法。

  • 抽象主题

    ServletContextEventSource
    HttpSessionEventSource
    
  • 具体主题

    ServletContext 
    HttpSession
    ServletRequest
    //Servlet容器在启动时会扫描并收集所有监听器实例,将其注册到对应的具体主题(ServletContext)的监听器列表中
    
  • 抽象观察者

    ServletContextListener
    HttpSessionContextListener
    ServletRequestContextListener
    
  • 具体观察者:开发者实现的监听器。

  • ① 当ServletContext被创建时,容器会创建ServletContextEvent事件对象(通过该事件对象可以得到ServletContext)

  • ② 容器遍历ServletContext对应的监听器列表,调用每个监听器的contextInitialized(ServletContextEvent sce)方法,传递事件对象。

    //在contextInitialized(ServletContextEvent sce)方法里面得到ServletContext对象的两种方法
    方法一
    ServletContext context = (ServletContext) sce.getSource();
    方法二
    sce.getServletContext() 不用强转,直接获取事件源。
    
  1. ServletContext核心定位:是每个Web应用在Servlet容器中唯一的全局对象,一个Web应用对应一个ServletContext实例。监听器列表只是ServletContext众多功能中的一小部分。

    Filter 支持专属初始化参数
    Servlet 支持专属初始化参数
    Listener 不持专属初始化参数
    

    Listener 不持专属初始化参数,但是可以通过以下两种方式初始化:

    • ① 全局上下文参数

      <context-param>
          <param-name>db.url</param-name>
          <param-value>jdbc:mysql://localhost:3306/test</param-value>
      </context-param>
      
    • ② 自定配置文件传递

    //建议将db.properties放在配置文件路径
    InputStream is = context.getResourceAsStream("/WEB-INF/db.properties");
    Properties prop = new Properties();
    prop.load(is);
    
posted @ 2025-12-02 23:39  那就改变世界吧  阅读(4)  评论(0)    收藏  举报