加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 创业 > C语言 > 正文

Servlet3——Listener

发布时间:2020-12-15 01:19:55 所属栏目:C语言 来源:网络整理
导读:基本概念 当Web应用在Web容器中运行时,Web应用内部会不断的发生各种事件:如Web应用被启动,Web应用被停止,用户session开始,用户session结束等。通常来说,这些事件对开发者是透明的。实际上,Servlet中提供了大量的监听器来监听Web应用的状态,监听器就

基本概念

当Web应用在Web容器中运行时,Web应用内部会不断的发生各种事件:如Web应用被启动,Web应用被停止,用户session开始,用户session结束等。通常来说,这些事件对开发者是透明的。实际上,Servlet中提供了大量的监听器来监听Web应用的状态,监听器就是Listener。使用Listener只需要两步:

  1. 定义Listener的实现类

  2. 通过注解或者在web.xml文件中配置这个Listener

主要的监听器类

  1. ServletContextListener:用于监听Web容器的启动和关闭

  2. ServletContextAttributeListener:用于监听application范围内的属性变化

  3. ServletRequestListener:用于监听用户的请求

  4. ServletRequestAttributeListener:用于监听request范围内的属性变化

  5. HttpSessionListener:用于监听用户session的创建和销毁

  6. HttpSessionAttributeListener:用于监听session范围内的属性变化

举个栗子

//监听web容器的启动与关闭
@WebListener
public class ContextListener implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        System.out.println("Web容器开启");
    }
@Override
public void contextDestroyed(ServletContextEvent servletContextEvent) {
    System.out.println("Web容器关闭");
}

}

//监听application范围内属性的变化
@WebListener
public class ContextAttributeListener implements ServletContextAttributeListener {
@Override
public void attributeReplaced(ServletContextAttributeEvent servletContextAttributeEvent) {
String key = servletContextAttributeEvent.getName();
Object value = servletContextAttributeEvent.getValue();
System.out.println("application中替换了"+key+",值为:"+value);
}

@Override
public void attributeRemoved(ServletContextAttributeEvent servletContextAttributeEvent) {
    String key = servletContextAttributeEvent.getName();
    Object value = servletContextAttributeEvent.getValue();
    System.out.println("application中删除了"+key+",值为:"+value);
}

@Override
public void attributeAdded(ServletContextAttributeEvent servletContextAttributeEvent) {
    String key = servletContextAttributeEvent.getName();
    Object value = servletContextAttributeEvent.getValue();
    System.out.println("application中增加了"+key+",值为:"+value);
}

}

其他的使用方法都是类似的。下一节,咱们看一下JSP2的特性

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读