Servlet监听器的使用

时间:2023-03-10 06:48:52
Servlet监听器的使用

Servlet监听器的使用

制作人:全心全意

在Servlet技术中已经定义了一些事件,并且可以针对这些事件来编写相关的事件监听器,从而对事件做出相应的处理。例如,想要在Web应用程序启动和关闭时来执行一些任务(如数据库连接的建立和释放),或者想要监控Session的创建和销毁,那么就可以通过监听器来实现。

Servlet监听器简介

监听器的作用是监听Web容器的有效期事件,因此它是由容器管理的。利用Listener接口监听在容器中的某个执行程序,并且根据其应用程序的需求做出适当的响应。

Servlet和JS中的8个Listener接口和6个Event类

Listener接口 Event类
    ServletContextListener     ServletContextEvent
    ServletContextAttributeListener     ServletContextAttributeEvent
    HttpSessionListener     HttpSessionEvent
    HttpSessionActivationListener
    HttpSessionAttributeListener     HttpSessionBindingEvent
    HttpSessionBindingListener
    ServletResquestListener     ServletResquestEvent
    ServletRequestAttributeListener     ServletRequestAttributeEvent

Servlet监听器的原理

Servlet监听器是当今Web应用开发的一个重要组成部分。它是在Servlet2.3规范中的Servlet过滤器一起引入的,并且在Servlet2.4规范中对其进行了较大的改进,主要就是用来对Web应用进行监听和控制的,极大地增强了Web应用的事件处理能力。

Servlet监听器的功能比较接近Java的GUI程序的监听器,可以监听由于Web应用中状态改变而引起的Servlet容器产生的相应事件,然后接受并处理这些事件。

Servlet上下文监听

Servlet上下文监听可以监听ServletContext对象的创建、删除以及属性添加、删除和修改操作,该监听器需要用到以下两个接口。

  • ServletContextListener接口

该接口存放在javax.servlet包内,它主要实现监听ServletContext的创建和删除。ServletContextListener接口提供了两个方法,它们也被称为“Web应用程序的生命周期方法”。下面分别进行介绍。

  contextInitialized(ServletContextEvent event)方法:通知正在收听的对象,应用程序已将被加载及初始化。

  contextDestroyed(ServletContextEvent event)方法:通知正在收听的对象,应用程序已经被载出,即关闭。

  • ServletAttributeListener接口

该接口存放在javax.servlet包内,主要实现监听ServletContext属性的增加、删除和修改。ServletAttributeListener接口提供了以下3个方法。

  attributeAdded(ServletContextAttributeEvent event)方法:当有对象加入Application的范围时,通知正在收听的对象。

  attributeReplaced(ServletContextAttributeEvent event)方法:当在Application的范围有对象取代另一个对象时,通知正在收听的对象。

  attributeRemoved(ServletContextAttributeEvent event)方法:当有对象从Application的范围移除时,通知正在收听的对象。

HTTP会话监听

HTTP会话监听(HttpSession)信息,有4个接口可以进行监听。

  • HttpSessionListener接口

HttpSessionListener接口实现监听HTTP会话创建、销毁。HttpSessionListener接口提供了两个方法。

  sessionCreated(HttpSessionEvent event)方法:通知正在收听的对象,session已经被加载及初始化。

  sessionDestroyed(HttpSessionEvent event)方法:通知正在收听的对象,session已经被载出(HttpSessionEvent类的主要方法是getSession(),可以使用该方法回传一个session对象。)

  • HttpSessionActivationListener接口

HttpSessionActivationListener接口实现监听HTTP会话active和passivate。HttpSessionActivationListener接口提供了以下3个方法。

  attributeAdded(HttpSessionBindingEvent event)方法:当有对象加如session的范围时,通知正在收听的对象。

  attributeReplaced(HttpSessionBindingEvent event)方法:当在session的范围有对象取代另一个对象时,通知正在收听的对象。

  attributeRemoved(HttpSessionBindingEvent event)方法:当有对象从session的范围移除时,通知正在收听的对象(HttpSessionBindingEvent类主要有3个方法:getName()、getSession()和getValues())。

  • HttpBindingListener接口

HttpBindingListener接口实现监听HTTP会话中对象的绑定信息。它是唯一不需要在web.xml中设定Listener的。HttpBindingListener接口提供以下两个方法。

  valueBound(HttpSessionBindingEvent event)方法:当有对象加入session范围内时会被自动调用。

  valueUnBound(HttpSessionBindingEvent event)方法:当有对象从session的范围内移除时会被自动调用。

  • HttpSessionAttributeListener接口

HttpSessionAttributeListener接口实现监听HTTP会话中属性的设置请求。HttpSessionAttributeListener接口提供以下两个方法。

  sessionDidActivate(HttpSessionEvent event)方法:通知正在收听的对象,它的session已经变为有效状态。

  sessionWillPassivate(HttpSessionEvent event)方法:通知正在收听的对象,它的session已经变为无效状态。

Servlet请求监听

在Servlet2.4规范中新增加了一个技术,就是可以监听客户端的请求。一旦能够在监听程序中获取客户端的请求,就可以对请求进行统一处理。要实现客户端的请求和请求参数设置的监听需要实现两个接口。

  • ServletRequestListener接口

ServletRequestListener接口提供了以下两个方法。

  requestInitalized(ServletRequestEvent event)方法:通知正在收听的对象,ServletRequest已经被加载及初始化。

  requestDestroyed(ServletRequestEvent event)方法:通知正在收听的对象,ServletRequest已经被载出,即关闭。

  • ServletRequestAttributeListener接口

ServletRequestAttribute接口提供了以下3个方法。

  attributeAdded(ServletRequestAttributeEvent event)方法:当有对象加入request的范围时,通知正在收听的对象。

  attributeReplaced(ServletRequestAttributeEvent event)方法:当在request的范围内有对象取代另一个对象时,通知正在收听的对象。

  attributeRemoved(ServletRequestAttributeEvent event)方法:当有对象从request的范围移除时,通知正在收听的对象。

Servlet监听器的使用实例

实例1:监听统计在线人数

UserInfoList类:用在存储在线用户和对在线用户的具体操作。

package com.zq;

import java.util.Vector;

public class UserInfoList {
private static UserInfoList user = new UserInfoList();
private Vector vector = null; public UserInfoList() {
this.vector = new Vector();
} public static UserInfoList getInstance() {
return user;
} // 增加用户
public boolean addUserInfo(String user) {
if (user != null) {
this.vector.add(user);
return true;
} else {
return false;
}
} // 获取用户列表
public Vector getList() {
return vector;
} // 移除用户
public void removeUserInfo(String user) {
if (user != null) {
this.vector.removeElement(user);
}
}
}

UserInfoTrace监听类:当有对象加入session时,valueBound()方法会自动被执行;当有对象从session中移除时,valueUnbound()方法会被自动执行,在valueBound()和valueUnbound()方法中都加入了输出信息的功能,可使用户在控制台中更清楚地了解执行过程。

package com.zq;

import javax.servlet.http.HttpSessionBindingEvent;

public class UserInfoTrace
implements javax.servlet.http.HttpSessionBindingListener { private String user;
private UserInfoList container = UserInfoList.getInstance(); public UserInfoTrace() {
user = "";
} // 设置在线监听人员
public void setUser(String user) {
this.user = user;
} // 获取在线监听
public String getUser() {
return this.user;
} public void valueBound(HttpSessionBindingEvent arg0) {
System.out.println("上线" + this.user); } public void valueUnbound(HttpSessionBindingEvent arg0) {
System.out.println("下线" + this.user);
if (user != "") {
container.removeUserInfo(user);
}
} }

index.jsp页面:用于放置增加在线用户的表单

<%@ 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>使用监听查看在线用户</title>
</head>
<script language="javascript">
function checkEmpty(form) {
for (i = 0; i < form.length; i++) {
if (form.elements[i].value == "") {
alert("表单信息不能为空");
return false;
}
}
}
</script>
<body>
<form name="form" method="post" action="showUser.jsp"
onSubmit="return checkEmpty(form)">
<input type="text" name="user"><br> <br> <input
type="submit" name="Submit" value="登录">
</form> </body>
</html>

showUser.jsp页面:用于接收index.jsp页面表单提交的用户,在在线用户列表中添加此用户,并显示所有在线用户。

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="java.util.*"%>
<%@ page import="com.zq.*"%>
<!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>显示用户</title>
</head>
<body>
<%
UserInfoList list = UserInfoList.getInstance();
UserInfoTrace ut = new UserInfoTrace();
String name = request.getParameter("user");
ut.setUser(name);
session.setAttribute("list", ut);
list.addUserInfo(ut.getUser());
session.setMaxInactiveInterval(10);
//session最大时限为10秒
%>
<textarea rows="8" cols="20">
<%
Vector vector = list.getList();
if (vector != null && vector.size() > 0) {
for (int i = 0; i < vector.size(); i++) {
out.println(vector.elementAt(i));
}
}
%>
</textarea>
<br>
<a href="loginOut.jsp">退出</a> </body>
</html>

loginOut.jsp页面:用于放置在showUser.jsp页面中点击退出按钮后的处理内容,并在处理后,重定向页面到index.jsp页面。

<%@ 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">
</head>
<body>
<%
session.invalidate();
%>
</body>
<script>
parent.location.href = 'index.jsp';
</script>
</html>