
(listener)监听器的使用
一:Listener的定义与作用
监听器Listener就是在application,session,request三个对象创建,销毁,或者往其中添加修改删除属性时自动执行代码的功能组件。Listener是Servlet的监听器,可以监听客户端的请求,服务端的操作等。
二:Listener的分类与使用
1. ServletContext监听
ServletContextListener接口:用于对Servlett整个上下文进行监听(创建,销毁)。
public void contextInitialized(ServletContextEvent sce) //上下文初始化
public void contextDestoryed(ServletContextEvent sce) //上下文销毁
public ServletContext getServletContext(); //取得一个ServletContext(application)对象
ServletContextAttributeListener接口:对Servlet上下文属性的监听(增删改属性)。
public void attributeAdded(ServletContextAttributeEvent scab);//增加属性
public void attributeRemoved(ServletContextAttributeEvent scab);//属性删除
public void attributeRepalced(ServletContextAttributeEvent scab);属性替换
2.Session监听
HttpSessionListener接口:对session的整体状态的监听。
public void sessionCreated(HttpSessionEvent se); //session创建(可以统计在线人数)
public void sessionDestoryed(HttpSessionEvent se); //session销毁
HttpSessionAttributeListener接口:对session的属性监听。
public void attributeAdded(HttpSessionBindingEvent se); //增加属性
public void attributeRemoved(HttpSessionBindingEvent se);//删除属性
public void attributeReplaced(HttpSessionBindingEvent se);//替换属性
3.Request监听
ServletRequestListener:用于对Request请求进行监听(创建,销毁)
public void requestInitialized(ServletRequestEvent sre);//request初始化
public void requesyDestoryed(ServletRequestEvent sre);//request销毁
ServletRequestAttributeListener:对Request属性的监听(增删改属性)。
4.在web.xml中配置
Listener的配置信息必须在Filter和Servlet的配置之前,Listener的初始化(ServletContextListener初始化)比Servlet和Filetr都优先,而销毁比Servlet和Filter都慢。
|
|
5.Spring监听器ContextLoaderListener的作用
ContextLoaderListener的作用就是启动Web容器时,自动装配ApplicationContext的配置信息。因为它实现了ServletContextListener这个接口,在web.xml配置这个监听器,启动容器时,就会默认执行它实现的方法。
ContextLoaderListener如何查找ApplicationContext.xml的配置位置以及配置多个xml:如果在web.xml中不写任何参数配置信息,默认的路径是”/WEB-INF/applicationContext.xml”,在WEB-INF目录下创建的xml文件的名称必须是applicationContext.xml(在MyEclipse中把xml文件放置在src目录下)。如果是要自定义文件名可以在web.xml里加入contextConfigLocation这个context参数。
|
|