监听器(Listener)

来源:互联网 发布:围棋软件单机版 编辑:程序博客网 时间:2024/05/16 11:38

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 implementsServletContextAttributeListener {    //当增加一个属性值时,该方法得到调用public void attributeAdded(ServletContextAttributeEvent scab) {// TODO Auto-generated method stubSystem.out.println("attributeAdded:");System.out.println("name: " + scab.getName() + " value :" + scab.getValue());}    //当移除一个属性值时,该方法得到调用public void attributeRemoved(ServletContextAttributeEvent scab) {// TODO Auto-generated method stubSystem.out.println("attributeRemoved");System.out.println("name: " + scab.getName() + " value :" + scab.getValue());}    //当替换一个属性值时,该方法得到调用public void attributeReplaced(ServletContextAttributeEvent scab) {// TODO Auto-generated method stubSystem.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 都慢










原创粉丝点击