enums=ul.getUserList();
int i=0;
while(enums.hasMoreElements())
{
out.println(enums.nextElement());
out.println(" ");
if(++i==10)
{
out.println("
");
}
}
out.println("
当前在线的用户数:"+i);
out.println("
退出登录");
out.close();
}
}
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException,IOException
{
doGet(req,resp);
}
}
*********** LogoutServlet.java ************
package org.sunxin.lesson.jsp.ch09.online;
import javax.servlet.*;
import java.io.*;
import javax.servlet.http.*;
public class LogoutServlet extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException,IOException
{
resp.setContentType("text/html;charset=gb2312");
HttpSession session=req.getSession();
User user=(User)session.getAttribute("user");
session.invalidate();
PrintWriter out=resp.getWriter();
out.println("");
out.println(user.getName()+",你已退出登录
");
out.println("重新登录");
out.println("");
out.close();
}
}
*********** User.java ************
package org.sunxin.lesson.jsp.ch09.online;
import javax.servlet.http.HttpSessionBindingListener;
import javax.servlet.http.HttpSessionBindingEvent;
public class User implements HttpSessionBindingListener
{
private String name;
private UserList ul=UserList.getInstance();
public User()
{
}
public User(String name)
{
this.name=name;
}
public void setName(String name)
{
this.name=name;
}
public String getName()
{
return name;
}
public void valueBound(HttpSessionBindingEvent event)
{
ul.addUser(name);
}
public void valueUnbound(HttpSessionBindingEvent event)
{
ul.removeUser(name);
}
}
*********** UserList.java ************
package org.sunxin.lesson.jsp.ch09.online;
import java.util.Vector;
import java.util.Enumeration;
public class UserList
{
private static final UserList userList=new UserList();
private Vectorv;
private UserList()
{
v=new Vector();
}
public static UserList getInstance()
{
return userList;
}
public void addUser(String name)
{
if(name!=null)
v.addElement(name);
}
public void removeUser(String name)
{
if(name!=null)
v.remove(name);
}
public EnumerationgetUserList()
{
return v.elements();
}
public int getUserCount()
{
return v.size();
}
}
****************************
Java代码的思路是将所有登陆用户放到集合中。
用户登陆成功就添加到用户列表,用户退出就从用户列表中移出。
lz 注意User类所实现的接口以及其中以下两个方法:
//对象被绑定到session中时通知该对象
public void valueBound(HttpSessionBindingEvent event)
{
ul.addUser(name);
}
//从session中删除对象时通知该对象
public void valueUnbound(HttpSessionBindingEvent event)
{
ul.removeUser(name);
}
【编辑推荐】
【责任编辑:王观 TEL:(010)68476606】
点赞 0