zoukankan      html  css  js  c++  java
  • Servlet 监听器Listner

    定义:

         专门用于对其他对象身上发生的事件或状态改变进行监听和相应处理的对象,当被监视的对象发生情况时,立即采取相应的行动。

         Servlet 规范为每种事件监听器都定义了相应的接口,它用于监听 web 应用程序中的 ServletContext, HttpSession 和 ServletRequest 等域对象的创建与销毁事件。

    接口实现类:

       编写的事件监听器程序只需实现这些接口

    public class HelloServletContextListner 
    	implements ServletContextListener, ServletRequestListener, HttpSessionListener {
    
    	@Override
    	public void contextInitialized(ServletContextEvent sce) {
    		System.out.println("ServletContext 对象被创建。 " + sce.getServletContext());
    	}
    
    	@Override
    	public void contextDestroyed(ServletContextEvent sce) {
    		System.out.println("ServletContext 对象被销毁。" + sce.getServletContext());
    	}
    
    	@Override
    	public void sessionCreated(HttpSessionEvent se) {
    		System.out.println("HttpSession 被创建。");
    	}
           
    	@Override
    	public void sessionDestroyed(HttpSessionEvent se) {
    		// TODO Auto-generated method stub
    		System.out.println("HttpSession 被销毁");
    	}
    
    	@Override
    	public void requestDestroyed(ServletRequestEvent sre) {
    		// TODO Auto-generated method stub
    		System.out.println("ServletRequest 被销毁");
    	}
    
    	@Override
    	public void requestInitialized(ServletRequestEvent sre) {
    		// TODO Auto-generated method stub
    		System.out.println("ServletRequest 被创建");
    	}
    
    }

    声明注册:

          Servlet事件监听器需要在 web 应用程序的 web.xml 文件中进行注册

    	<!-- 配置监听 -->
    	<listener>
    		<listener-class>com.demo.listener.HelloServletContextListner</listener-class>
    	</listener>
    

    应用场景:  

          1.ServletContextListener 是最常用的 Listener, 可以在当前 WEB 应用被加载时对当前 WEB 应用的相关资源进行初始化操作: 创建 Spring 的 IOC 容器,

          2.HttpSessionListener,统计当前在线人数列表

  • 相关阅读:
    linux环境下的时间编程
    golang1.13中重要的新特新
    vs2019+cmake实现Linux远程开发
    现代c++与模板元编程
    一个commit引发的思考
    golang中判断两个slice是否相等
    c++性能测试工具:计算时间复杂度
    c++性能测试工具:google benchmark入门(二)
    使用vs2019进行Linux远程开发
    智能指针和二叉树(3):图解查找和删除
  • 原文地址:https://www.cnblogs.com/walkwithmonth/p/9821038.html
Copyright © 2011-2022 走看看