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

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{

	@Override
	public void attributeAdded(HttpSessionBindingEvent arg0) {
		System.out.println("添加属性");
		
	}

	@Override
	public void attributeRemoved(HttpSessionBindingEvent arg0) {
		System.out.println("移除属性");
		
	}

	@Override
	public 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日















评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值