Java监听器Listener使用说明

来源:互联网 发布:泰山学院网络管理系统 编辑:程序博客网 时间:2024/06/05 00:25

1、什么是Java监听器

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

 

2、Listener接口分类

1.1> ServletContextListener监听ServletContext对象

1.2> ServletContextAttributeListener监听对ServletContext属性的操作,比如增加、删除、修改

 

2.1> HttpSessionListener监听Session对象

2.2> HttpSessionActivationListener监听HTTP会话的activepassivate情况,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>

原创粉丝点击