在线列表设计


首先设计一个类继承,application和session接口

代码如下:
=======================================================

package com.t48.action;


import javax.servlet.*;

import java.util.*;

import javax.servlet.http.*;

public class onlineDemo
implements javax.servlet.ServletContextListener,
javax.servlet.http.HttpSessionListener,HttpSessionAttributeListener
{

// 声明一个ServletContext对象
private ServletContext application = null ;
public void contextInitialized(ServletContextEvent sce)
{
// 容器初始化时,向application中存放一个空的容器
this.application = sce.getServletContext() ;
this.application.setAttribute("alluser",new ArrayList()) ;
}

public void contextDestroyed(ServletContextEvent sce)
{}

public void sessionCreated(HttpSessionEvent se)
{}
public void sessionDestroyed(HttpSessionEvent se)
{
// 将用户名称从列表中删除
List l = (List)this.application.getAttribute("alluser") ;
String value = (String)se.getSession().getAttribute("uname") ;
l.remove(value) ;
this.application.setAttribute("alluser",l) ;
}

public void attributeAdded(HttpSessionBindingEvent se)
{
// 如果登陆成功,则将用户名保存在列表之中
List l = (List)this.application.getAttribute("alluser") ;
l.add(se.getValue()) ;
this.application.setAttribute("alluser",l) ;
}
public void attributeRemoved(HttpSessionBindingEvent se)
{}
public void attributeReplaced(HttpSessionBindingEvent se)
{}

}
=========================

<%@ page contentType="text/html;charset=gb2312"%>
<%@ page import="java.util.*"%>
<form action="online.jsp" method="post">
用户名:
<input type="text" name="name">
<input type="submit" value="登陆">
<a href="logout.jsp">注销</a>
</form>
<!-- 向session接收输入的用户名 -->
<%
if(request.getParameter("name")!=null)
{
session.setAttribute("uname",request.getParameter("name")) ;
}
%>
<h2>在线人员</h2>
<hr>
<%
List l = (List)application.getAttribute("alluser") ;
Iterator iter = l.iterator() ;
while(iter.hasNext())
{
%>
<li><%=iter.next()%>
<%
}
%>
==========================

web.xml


<!-- 在线人员列表 -->

<listener>
<listener-class>com.t48.action.onlineDemo</listener-class>
</listener>

你可能感兴趣的:(html,tomcat,Web,xml,servlet)