显示在线人员的思线
1.服务器一启动就创建一个List<String>名字叫onlinePersion,放在application中
2.只要有一个浏览器访问进来,就创建一个随机的用户名"游客***"
更改游客名称为admin
4.给一个浏览器生成在线用户名的同时,把这个浏览器生成的在线用户记录下来。
然后迭代在线用户列表在线用户列表的索引位置.
然后set(索引位置,登录的用户名)。
整个源代码下载地址
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());
调用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);
然后迭代在线用户列表在线用户列表的索引位置.
然后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");
}
}
整个源代码下载地址