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");
}
}
整個源代碼下載地址