---
title: "Java监听器Listener"
author: "windpoplar"
date: "2017-02-26T18:24:36Z"
tags: []
categories: ["互联网"]
slug: "java-listener"
draft: false
lastmod: "2017-02-26T18:24:36Z"
id: 2359157
url: "https://windpoplar.iteye.com/blog/2359157"
---

1、什么是[Java](http://lib.csdn.net/base/javase "Java SE知识库")监听器

监听器也叫Listener，是Servlet的监听器，它可以监听客户端的请求、服务端的操作等。通过监听器，可以自动激发一些操作，比如监听在线的用户的数量。

 

2、Listener接口分类

1.1&gt; ServletContextListener监听ServletContext对象

1.2&gt; ServletContextAttributeListener监听对ServletContext属性的操作，比如增加、删除、修改

  

2.1&gt; HttpSessionListener监听Session对象

2.2&gt; HttpSessionActivationListener监听HTTP会话的active和passivate情况，passivate是指非活动的session被写入持久设备（比如硬盘），active相反。

2.3&gt; HttpSessionAttributeListener监听Session中的属性操作

 

3.1&gt; ServletRequestListener监听Request对象

3.2&gt; ServletRequestAttributeListener监听Requset中的属性操作

 

3、Java代码

   1.1&gt; ServletContextListener

 

contextInitialized(ServletContextEvent) 初始化时调用

contextDestoryed(ServletContextEvent) 销毁时调用，即当服务器重新加载时调用

 

   2.1&gt;HttpSessionListener

 

 

sessionCreated(HttpSessionEvent) 初始化时调用

sessionDestoryed(HttpSessionEvent) 销毁时调用，即当用户注销时调用

 

   3.1&gt;ServletRequestListener

 

requestinitialized(ServletRequestEvent) 对实现客户端的请求进行监听

requestDestoryed(ServletRequestEvent) 对销毁客户端进行监听，即当执行request.removeAttribute("XXX")时调用

 

 

4、Demo

1&gt;创建Java类，实现对应的接口

 

 

package com.lacom;

 

import javax.servlet.http.HttpSessionEvent;

import javax.servlet.http.HttpSessionListener;

 

public class TestSessionListener implements HttpSessionListener {

 

@Override

public void sessionCreated(HttpSessionEvent event) {

// session 创建时执行的操作

// 例如：在线人数+1

 

}

 

@Override

public void sessionDestroyed(HttpSessionEvent event) {

// session 销毁时执行的操作

// 例如：在线人数-1

 

}

 

}

 

2&gt;在web.xml中配置

 

 

&lt;?xml version="1.0" encoding="UTF-8"?&gt;

&lt;web-appweb-appversion="2.5" 

xmlns="http://java.sun.com/xml/ns/javaee" 

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xmlns:web="http://java.sun.com/xml/ns/javaee/web-app\_2\_5.xsd"

xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app\_2\_5.xsd"&gt;

&lt;listener&gt;

&lt;listener-class&gt;com.lacom.TestSessionListener&lt;/listener-class&gt;

&lt;/listener&gt;

&lt;/web-app&gt;

 

5、Java项目中用到的[spring](http://lib.csdn.net/base/javaee "Java EE知识库")监听器

ContextLoaderListener

作用：

启动Web容器时，自动装配ApplicationContext的配置信息。

用法：

第一种：直接将applicationContext.xml（spring的配置文件）放到/WEB-INF下，只在web.xml中声明一个listener

&lt;listener&gt;

&lt;listener-class&gt;

org.springframework.web.context.ContextLoaderListener

&lt;/listener-class&gt;

&lt;/listener&gt;

第二种：将之放到classpath下，但是此时要在web.xml中加入&lt;context-param&gt;，用它来指明你的applicationContext.xml的位置以供web容器来加载。如果有多个xml文件，可以写在一起并用“,”号分隔。例如近铁项目中的配置：

 

 

 

Log4jConfigListener

好处：  
   1. 动态的改变记录级别和策略，不需要重启Web应用，如《Effective Enterprise Java》所说。  
   2. 把log文件定在 /WEB-INF/logs/ 而不需要写绝对路径。  
因为 系统把web目录的路径压入一个叫webapp.root的系统变量。这样写log文件路径时不用写绝对路径了.  
log4j.appender.logfile.File=${webapp.root}/WEB-INF/logs/myfuse.log  
   3. 可以把log4j.properties和其他properties一起放在/WEB-INF/ ，而不是Class-Path。  
   4.log4jRefreshInterval为60000表示 开一条watchdog线程每60秒扫描一下配置文件的变化;

用法：  
   在web.xml 添加  
    &lt;context-param&gt;  
        &lt;param-name&gt;log4jConfigLocation&lt;/param-name&gt;  
        &lt;param-value&gt;WEB-INF/log4j.properties&lt;/param-value&gt;  
    &lt;/context-param&gt;

    &lt;context-param&gt;  
        &lt;param-name&gt;log4jRefreshInterval&lt;/param-name&gt;  
        &lt;param-value&gt;60000&lt;/param-value&gt;  
    &lt;/context-param&gt;

    &lt;listener&gt;  
        &lt;listener-class&gt;org.springframework.web.util.Log4jConfigListener&lt;/listener-class&gt;  
    &lt;/listener&gt;