php lister,java listers怎么用

Java listers的使用步骤:1、通过实现具体接口创建实现类(可实现多个监听器接口)。2、直接用@WebListener注解修饰实现类,配置实现类成为监听器;或者通过web.xml方式配置实现类成为监听器。

d96d3048945fabd13c72ca5fdd1c5aea.png

Java listers是监听器的意思,用于监听Web应用的内部事件的实现类。可以监听用户session的开始与结束,用户请求的到达等等,当事件发生时,会回调监听器的内部方法。

使用Listener步骤

通过实现具体接口创建实现类(可实现多个监听器接口)

配置实现类成为监听器,有两种配置方式:

直接用@WebListener注解修饰实现类

通过web.xml方式配置,代码如下:

com.zrgk.listener.MyListener

常用Web事件监听器接口

1. ServletContextListener

该接口用于监听Web应用的启动与关闭

该接口的两个方法:contextInitialized(ServletContextEvent event); // 启动web应用时调用

contextDestroyed(ServletContextEvent event); // 关闭web应用时调用

如何获得application对象:ServletContext application = event.getServletContext();

示例:@WebListener

public class MyServetContextListener implements ServletContextListener{

//web应用关闭时调用该方法

@Override

public void contextDestroyed(ServletContextEvent event) {

ServletContext application = event.getServletContext();

String userName = application.getInitParameter("userName");

System.out.println("关闭web应用的用户名字为:"+userName);

}

//web应用启动时调用该方法

@Override

public void contextInitialized(ServletContextEvent event) {

ServletContext application = event.getServletContext();

String userName = application.getInitParameter("userName");

System.out.println("启动web应用的用户名字为:"+userName);

}

}

2. ServletContextAttributeListener

该接口用于监听ServletContext范围(application)内属性的改变。

该接口的两个方法:attributeAdded(ServletContextAttributeEvent event);//当把一个属性存进application时触发

attributeRemoved(ServletContextAttributeEvent event);//当把一个属性从application删除时触发

attributeReplaced(ServletContextAttributeEvent event);//当替换application内的某个属性值时触发

如何获得application对象:ServletContext application = event.getServletContext();

示例:@WebListener

public class MyServletContextAttributeListener implements ServletContextAttributeListener{

//向application范围内添加一个属性时触发

@Override

public void attributeAdded(ServletContextAttributeEvent event) {

String name = event.getName();//向application范围添加的属性名

Object val = event.getValue(); //向application添加的属性对应的属性值

System.out.println("向application范围内添加了属性名为:"+name+",属性值为:"+val+"的属性");

}

//删除属性时触发

@Override

public void attributeRemoved(ServletContextAttributeEvent event) {

// ...

}

//替换属性值时触发

@Override

public void attributeReplaced(ServletContextAttributeEvent event) {

// ...

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值