Listener是Servlet的监听器,可以监听客户端的请求,服务端的操作等
定义监听器类的步骤
1)要想让一个类成为监听器类,就必须去实现监听接口,及实现接口的方法,
常见的监听接口如下:
- ServletContextListener
- ServletContextAtrributeListener
- HttpSessionListener
- HttpSessionAttributeListener
2)在web.xml中配置相应的信息
例如
<一>定义一个监听器类:
- package com.servlet.listener;
-
- import javax.servlet.ServletContextEvent;
- import javax.servlet.ServletContextListener;
-
-
-
- public class MyServletContextListener implements ServletContextListener {
-
-
- public void contextInitialized(ServletContextEvent sce )
- {
- System.out.println("Listener contextInitialized : "+ sce.getServletContext());
- }
-
- 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) {
-
-
- System.out.println("attributeAdded:");
-
- System.out.println("name: " + scab.getName() + " value :" + scab.getValue());
-
- }
-
-
- public void attributeRemoved(ServletContextAttributeEvent scab) {
-
- System.out.println("attributeRemoved");
-
- System.out.println("name: " + scab.getName() + " value :" + scab.getValue());
-
- }
-
-
- public void attributeReplaced(ServletContextAttributeEvent scab) {
-
-
- System.out.println("attributeReplaced");
-
-
- 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 都慢
本文转自:http://blog.csdn.net/hzc543806053/article/details/7450812