在web.xml中配置监听器。注意:监听器>过滤器>serlvet,配置的时候要注意先后顺序
1、什么是Java监听器
监听器也叫Listener,是Servlet的监听器,它可以监听客户端的请求、服务端的操作等。通过监听器,可以自动激发一些操作,比如监听在线的用户的数量。
2、Listener接口分类
1.1> ServletContextListener监听ServletContext对象
1.2> ServletContextAttributeListener监听对ServletContext属性的操作,比如增加、删除、修改
2.1> HttpSessionListener监听Session对象
2.2> HttpSessionActivationListener监听HTTP会话的active和passivate情况,passivate是指非活动的session被写入持久设备(比如硬盘),active相反。
2.3> HttpSessionAttributeListener监听Session中的属性操作
3.1> ServletRequestListener监听Request对象
3.2> ServletRequestAttributeListener监听Requset中的属性操作
3、Java代码
1.1> ServletContextListener
contextInitialized(ServletContextEvent) 初始化时调用
contextDestoryed(ServletContextEvent) 销毁时调用,即当服务器重新加载时调用
2.1>HttpSessionListener
sessionCreated(HttpSessionEvent) 初始化时调用
sessionDestoryed(HttpSessionEvent) 销毁时调用,即当用户注销时调用
3.1>ServletRequestListener
requestinitialized(ServletRequestEvent) 对实现客户端的请求进行监听
requestDestoryed(ServletRequestEvent) 对销毁客户端进行监听,即当执行request.removeAttribute("XXX")时调用
4、Demo
1>创建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>在web.xml中配置
<?xml version="1.0" encoding="UTF-8"?>
<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">
<listener>
<listener-class>com.lacom.TestSessionListener</listener-class>
</listener>
</web-app>
5、Java项目中用到的spring监听器
ContextLoaderListener
作用:
启动Web容器时,自动装配ApplicationContext的配置信息。
用法:
第一种:直接将applicationContext.xml(spring的配置文件)放到/WEB-INF下,只在web.xml中声明一个listener
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
第二种:将之放到classpath下,但是此时要在web.xml中加入<context-param>,用它来指明你的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 添加
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>WEB-INF/log4j.properties</param-value>
</context-param>
<context-param>
<param-name>log4jRefreshInterval</param-name>
<param-value>60000</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>