Java Web編程中則是在web.xml中配置所要監聽的事件,由web容器在特定事件發生時自動的調用特定的實現監聽器接口的類的特定方法。
servlet2.5版本設計了8個監聽器,涉及了6種事件類型。
分別是4個監聽器接口監聽會話活動,兩個監聽器監聽與ServletContext對象相關的事件,還有兩個監聽器接口監聽與HttpServletRequest相關的事件。
主要四個是HttpSession接口:HttpSessionListener,HttpSessionAttributeListener,HttpSessionBindingListener以及HttpSessionOnActivationListener。
實例統計在線人數
新建一個Java類
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
/*
* 當有一個新的用戶訪問這個Web應用的時候,Web容器自動調用sessionCreated()方法。
* 當用戶回話失效以後,Web容器又會自動調用sessionDestroyed()方法。
*
* */
public class CounterListener implements HttpSessionListener {
private static long onlineNumber = 0;
public static long getOnlineNumber(){
return onlineNumber;
}
public void sessionCreated(HttpSessionEvent se){
onlineNumber++;
}
public void sessionDestroyed(HttpSessionEvent se){
onlineNumber--;
}
}
該類實現了HttpSessionLisener接口。
編輯Web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<display-name></display-name>
<listener>
<listener-class>
webbook.chapter12.CounterListener
</listener-class>
</listener>
<welcome-file-list>
<welcome-file>display.jsp</welcome-file>
</welcome-file-list>
</web-app>
編輯display.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'display.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
當前應用一共有<%=webbook.chapter12.CounterListener.getOnlineNumber()%>人在線
</body>
</html>
注意jsp文件導入import包名類名,否則編譯不通過。