简介
Listener是监听器,它可以监听客户端的请求、服务端的操作等。通过监听器,可以自动激发一些操作
监听系统启动,做一些初始化动作比如监听在线的用户的数量
Listener 创建模板
创建的模板如下:
选择这个 整个生命周期的监测
package servlet;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
/**
* Application Lifecycle Listener implementation class ListenerTest
*
*/
public class ListenerTest implements HttpSessionListener {
/**
* Default constructor.
*/
public ListenerTest() {
// TODO Auto-generated constructor stub
}
/**
* @see HttpSessionListener#sessionCreated(HttpSessionEvent)
*/
public void sessionCreated(HttpSessionEvent se) {
// TODO Auto-generated method stub
}
/**
* @see HttpSessionListener#sessionDestroyed(HttpSessionEvent)
*/
public void sessionDestroyed(HttpSessionEvent se) {
// TODO Auto-generated method stub
}
}
添加对应的业务
package servlet;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
/**
* Application Lifecycle Listener implementation class ListenerTest
*
*/
public class ListenerTest implements HttpSessionListener {
private static int activeSessions = 0;
/**
* Default constructor.
*/
public ListenerTest() {
// TODO Auto-generated constructor stub
}
/**
* @see HttpSessionListener#sessionCreated(HttpSessionEvent)
*/
public void sessionCreated(HttpSessionEvent se) {
// TODO Auto-generated method stub
activeSessions++;
System.out.println("sessionCreated");
}
/**
* @see HttpSessionListener#sessionDestroyed(HttpSessionEvent)
*/
public void sessionDestroyed(HttpSessionEvent se) {
// TODO Auto-generated method stub
if (activeSessions>0) {
activeSessions--;
System.out.println("sessionDestroyed");
}
}
public static int getActiveSessions() {
return activeSessions;
}
}
webxml中添加listener
<listener>
<listener-class>servlet.ListenerTest</listener-class>
</listener>
jsp如下:
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ page import="servlet.ListenerTest"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP 'ApplicationTest.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>
在线人数为:<%=ListenerTest.getActiveSessions() %>
</body>
</html>