监听器:
package org.listenerdemo;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class OnlineUserList implements ServletContextListener,HttpSessionAttributeListener,HttpSessionListener
{
private ServletContext app = null;
public void contextInitialized(ServletContextEvent sce){
this.app = sce.getServletContext();
this.app.setAttribute("online",new TreeSet());//准备集合
}
public void contextDestroyed(ServletContextEvent sce){}
public void attributeAdded(HttpSessionBindingEvent se){
Set all = (Set) this.app.getAttribute("online");
all.add(se.getValue());
this.app.setAttribute("online",all);
}
public void attributeRemoved(HttpSessionBindingEvent se){
Set all = (Set) this.app.getAttribute("online");
all.remove(se.getSession().getAttribute("userid"));
this.app.setAttribute("online",all);
}
public void attributeReplaced(HttpSessionBindingEvent se){}
public void sessionCreated(HttpSessionEvent se){}
public void sessionDestroyed(HttpSessionEvent se){
Set all = (Set) this.app.getAttribute("online");
all.remove(se.getSession().getAttribute("userid"));
this.app.setAttribute("online",all);
}
}
/* web.xml 配置
<listener>
<listener-class>
org.listenerdemo.OnlineUserList
</listener-class>
</listener>
</servlet-mapping>
<session-config>
<session-timeout>1</session-timeout>
</session-config>
*/
登陆:
<%@ page contentType="text/html;charset=GBK"%>
<%@ page import="java.util.*"%>
<html>
<head>
<title>www.baidu.com</title>
</head>
<body>
<form action="login.jsp" method="post">
用户ID: <input type="text" name="userid">
<input type="submit" value="登陆">
</form>
<%
request.setCharacterEncoding("GBK");
%>
<%
String userid = request.getParameter("userid");
if(!(userid==null ||"".equals(userid))){
session.setAttribute("userid",userid);
response.sendRedirect("list.jsp");
}
%>
</body>
</html>
在线成员列表:
<%@ page contentType="text/html;charset=GBK"%>
<%@ page import="java.util.*"%>
<html>
<head>
<title>www.baidu.com</title>
</head>
<body>
<%
request.setCharacterEncoding("GBK");
%>
<%
Set all = (Set)this.getServletContext().getAttribute("online");
Iterator iter = all.iterator();
while(iter.hasNext()){
%>
<h3><%=iter.next()%></h3>
<%
}
%>
</body>
</html>
本页面用监听器实现了在线人员的列表显示,登陆后,session-timeou 为1分钟
在监听器中,实现了ServletContextListener,HttpSessionAttributeListener,HttpSessionListener 的个别方法,以实现人员的登陆与注销.
只在了解监听器(学习中.........)