Listener监听器


定义及作用
  监听器Listener就是在application,session,request三个对象创建、销毁或者往其中添加修改删除属性时自动执行代码的功能组件。
  Listener是Servlet的监听器,可以监听客户端的请求,服务端的操作等。
分类及使用
  1. ServletContext监听
    ServletContextListener:用于对Servlet整个上下文进行监听(创建、销毁),监听ServletContext对象的生命周期,实际上就是监听Web应用的生命周期。
    ServletContextAttributeListener:对Servlet上下文属性的监听(增删改属性),监听ServletContext范围内属性的变化

  2. Session监听
    Session属于http协议下的内容,接口位于javax.servlet.http.*下。
    HttpSessionListener接口:对Session的整体状态的监听。
    HttpSessionAttributeListener接口:对session属性的监听。

    session的销毁有两种情况
    1.session超时
    2.手工使session失效
    3. Request监听
      ServletRequestListener:用于对Request请求进行监听(创建、销毁)。
      ServletRequestAttributeListener:对Request属性的监听(增删改属性)
    4. 在web.xml中配置
       Listener配置信息必须在Filter和Servlet配置之前,Listener的初始化(ServletContentListener初始化)比Filter和Servlet都优先,而销毁比Filter和Servlet都慢。

应用实例
1. 利用HttpSessionListener统计最多在线用户人数

package com.zhen.Listener;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

/**
 * 统计最多在线数
 * */
public class HttpSessionListenerImpl implements HttpSessionListener {

    @Override
    public void sessionCreated(HttpSessionEvent se) {
    
        ServletContext app = se.getSession().getServletContext();
        int count = Integer.parseInt(app.getAttribute("onLineCount").toString());
        count++;
        app.setAttribute("onLineCount", count);
        int maxOnLineCount = Integer.parseInt(app.getAttribute("maxOnLineCount").toString());
        if (count > maxOnLineCount) {
            //记录最多人数是多少
            app.setAttribute("maxOnLineCount", count);
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            //记录在那个时刻达到上限
            app.setAttribute("date", df.format(new Date()));
        }
    }

    //session注销、超时时候调用,停止tomcat不会调用
    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
         ServletContext app = se.getSession().getServletContext();
            int count = Integer.parseInt(app.getAttribute("onLineCount").toString());
            count--;
            app.setAttribute("onLineCount", count);    
        
    }

}


2. Spring使用ContextLoaderListener加载ApplicationContext配置信息
ContextLoaderListener的作用是启动Web容器时,自动装配ApplicationContext的配置信息。因为它实现了ServletContextListener这个接口,在web.xml配置这个监听器,启动监听器是,就会默认执行它实现的方法。
ContextLoaderListener查找ApplicationContext.xml的配置位置:如果在web.xml中不写任何配置信息,默认的路径是在/WEB-INF下,名称必须为applicaitonContext.xml,但是开发中配置信息都是统一管理,放在统一位置,所以要使用<context-param>标签指定该文件所在位置,此时名称可以自定义,路径基本为WEB-INF/classes/spring/applicatoinContext.xml,也可以写为classpath:spring/applicaitonContext.xml

posted on 2017-03-11 23:03  嘣嘣嚓  阅读(249)  评论(0编辑  收藏  举报

导航