ServletContextListener,HttpSessionListener,ServletRequestListener监听器的使用,使用的详细步骤

来源:互联网 发布:淘宝代理的货怎样发货 编辑:程序博客网 时间:2024/05/07 14:24

1.概念

监听器:监听器就是一个实现特定接口的普通java程序,这个java程序专门用于监听另一个java对象的方法调用或属性改变。

2.作用域

在servlet中定义了多种类型的监听器,用于监听的事件源分别为:ServletContext,ServletRequesst,HttpSession这三个域对象。

3.类别

servlet中提供了八个监听器对上述对象进行监听。这八个监听器可以分为以下三种.

(1)监听三个作用域对象的创建和销毁

ServletContextListener 

HttpSessionListener

ServletRequestListener 

(2)监听三个作用域对象属性的变化

ServletContextAttributeListener
HttpSessionAttributeListener 
ServletRequestAttributeListener

(3)监听session中属性状态的变化

session中对象的状态有4种:绑定,移除绑定,钝化(序列化),活化(反序列化)。

绑定:对象添加到session中     setAttribute()

移除绑定:对象从session中被移除  removeAttribute()

序列化:对象被写到硬盘上(文件中)

反序列化:将文件中的数据读取到内存中

HttpSessionBindingListener(绑定和移除绑定)

HttpSessionActivationListener (序列化和反序列化)

4.使用步骤

(1)编写类,实现监听器接口

(2)在web.xml中注册监听器

<listener>  <listener-class>tm.change.listener.SltContextListener</listener-class></listener>


(3)在实现方法中编写我们要实现的效果。


5.示例

(1)我们以监听session的创建和销毁为例。

(2)编写HttpSessionAttrListener类,实现HttpSessionAttributeListener接口


public class HttpSessionAttrListener implements HttpSessionAttributeListener{@Overridepublic void attributeAdded(HttpSessionBindingEvent arg0) {System.out.println("添加属性");}@Overridepublic void attributeRemoved(HttpSessionBindingEvent arg0) {System.out.println("移除属性");}@Overridepublic void attributeReplaced(HttpSessionBindingEvent arg0) {System.out.println("替换属性");}}

(3)在web.xml中配置此监听器

  <listener>  <span style="white-space:pre"></span><listener-class>tm.change.listener.HttpSessionAttrListener</listener-class>  </listener>

(4)在首页index.jsp中setAttribute,然后removeAttribute


<%@ page language="java" contentType="text/html; charset=utf-8"    pageEncoding="utf-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title>Insert title here</title></head><body><%session.setAttribute("name", "shengxinjun");<span style="white-space:pre">session.removeAttribute("name");</span>%></body></html>

(5)启动项目

这个时候在Console中你会发现输出了“添加属性”和“移除属性”


更详细的使用请下载我百度云盘中的资料。大型实训3月22日















0 0
原创粉丝点击