监听器(Listener)

Listener是Servlet的监听器,可以监听客户端的请求,服务端的操作等


定义监听器类的步骤

1)要想让一个类成为监听器类,就必须去实现监听接口,及实现接口的方法,

常见的监听接口如下:

  • ServletContextListener
  • ServletContextAtrributeListener
  • HttpSessionListener
  • HttpSessionAttributeListener

2)在web.xml中配置相应的信息


例如

<一>定义一个监听器类

package com.servlet.listener;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

//ServletContextListener 监听器
//监听器的初始化比 servlet和filter 都优先,而销毁比servlet和filter 都慢
public class MyServletContextListener implements ServletContextListener {
	
	//初始化   当创建ServletContext时该方法得到调用       
	public void contextInitialized(ServletContextEvent sce )
	{
		System.out.println("Listener contextInitialized : "+ sce.getServletContext());
	}
	//当销毁ServletContext时该方法得到调用
	public void contextDestroyed(ServletContextEvent sce)
	{
		System.out.println("Listener contextDestroyed : "+ sce.getServletContext());
	}

}

定义完一个类后,下一步就要在web.xml中配置信息,该配置信息必须在filter和Servlet配置信息之前

<二>配置信息如下

  <listener>
    
    <listener-class>com.servlet.listener.MyServletContextListener</listener-class>
  
  </listener>


<一>在定义一个监听器类

package com.servlet.listener;

import javax.servlet.ServletContextAttributeEvent;
import javax.servlet.ServletContextAttributeListener;

public class MyServletContextAttributeListener implements
		ServletContextAttributeListener {
    
	//当增加一个属性值时,该方法得到调用
	public void attributeAdded(ServletContextAttributeEvent scab) {
		// TODO Auto-generated method stub
		
		System.out.println("attributeAdded:");
		
		System.out.println("name: " + scab.getName() + " value :" + scab.getValue());

	}
    
	//当移除一个属性值时,该方法得到调用
	public void attributeRemoved(ServletContextAttributeEvent scab) {
		// TODO Auto-generated method stub
		System.out.println("attributeRemoved");
		
		System.out.println("name: " + scab.getName() + " value :" + scab.getValue());

	}
    
	//当替换一个属性值时,该方法得到调用
	public void attributeReplaced(ServletContextAttributeEvent scab) {
		// TODO Auto-generated method stub
		
		System.out.println("attributeReplaced");
		
		//scab.getValue()返回被替换的值也就是 旧值
		System.out.println("name: " + scab.getName() + " value :" + scab.getValue());

	}

}

<二>web.xml的配置信息

  <listener>
    
    <listener-class>com.servlet.listener.MyServletContextAttributeListener</listener-class>
  
  </listener>


其它的定义监听器类和上面两个差不多


监听器的初始化(ServletContextListener的初始化方法)比 servlet和filter 都优先,而销毁比servlet和filter 都慢










  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值