使用listener显示在线人员的姓名

显示在线人员的思线
1.服务器一启动就创建一个List<String>名字叫onlinePersion,放在application中

    (监听application)

public class MyApplicationListener implements ServletContextListener {

	public void contextDestroyed(ServletContextEvent event) {
		// TODO Auto-generated method stub

	}

	/*
	 * web服务器一启动的时候该方法被调用
	 */
	public void contextInitialized(ServletContextEvent event) {
		// TODO Auto-generated method stub
		List<String> onlinePerson = new ArrayList<String>();
		
		//由事件源获取servletcontext
		ServletContext application = event.getServletContext();
		application.setAttribute("onlinePerson", onlinePerson);
	}

}

2.只要有一个浏览器访问进来,就创建一个随机的用户名"游客***"

    (监听session)

// 根据当前的:时分秒毫秒,生成随游客
SimpleDateFormat sdf = new SimpleDateFormat("HHmmssSSS");
String name = "游客" + sdf.format(new Date());


3.从application中把onlinePerson获取出来,

    调用add方法把随机用户名放在onlinePerson

// 通过session获取servletcontext
ServletContext application = event.getSession().getServletContext();
// application.getAttribute的返回值是Object,故需要向下转型
List<String> onlinePerson = (List<String>) application.getAttribute("onlinePerson");
onlinePerson.add(name);
// 把改变之后的在线人员,设置回去
application.setAttribute("onlinePerson", onlinePerson);

    更改游客名称为admin
    
4.给一个浏览器生成在线用户名的同时,把这个浏览器生成的在线用户记录下来。

         用session.setAttribute("onlineName",onlineName);

// 默认设置没有登录
HttpSession session = event.getSession();
session.setAttribute("isLogin", false);
session.setAttribute("onlineName", name);


5.登录成功的时候,把在线用户列表从application中取出,
    然后迭代在线用户列表在线用户列表的索引位置.
    然后set(索引位置,登录的用户名)。

    更新在线用户表

public class LoginServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html");

		// 简单去做,只要点击登录,就认为成功
		HttpSession session = request.getSession();
		session.setAttribute("isLogin", true);
		session.setAttribute("onlineName", "admin");

		// 把在线用户列表从application中取出
		ServletContext application = this.getServletContext();

		List<String> onlinePerson = (List<String>) application
				.getAttribute("onlinePerson");
		String onlineName = (String) request.getSession().getAttribute(
				"onlineName");

		// 迭代在线用户列表,寻找当前用户的索引位置.
		int index = -1;
		for (Iterator<String> iterator = onlinePerson.iterator(); iterator
				.hasNext();) {
			index++;

			String string = (String) iterator.next();
			if (string.equals(onlineName)) {
				break;
			}
		}

		// 找到
		if (index != -1) {
			onlinePerson.set(index, onlineName);
		}

		// 更新在线用户列表和onlineName
		application.setAttribute("onlinePerson", onlinePerson);
		request.getSession().setAttribute("onlineName", onlineName);

		response.sendRedirect("index.jsp");

	}

}

整个源代码下载地址

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值