1)创建一个OnLineCountListener监听器,统计在线人数
package xqyy.com.listener;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
public class OnLineCountListener implements ServletContextListener, HttpSessionListener, HttpSessionAttributeListener {
//声明一个servletContext对象
private ServletContext application=null;
@Override
public void attributeAdded(HttpSessionBindingEvent hsbe) {
//如果登录成功,则将用户名保存在列表中
List l=(List) this.application .getAttribute("alluser");
l.add(hsbe.getValue());
this.application.setAttribute("alluser", l);
}
@Override
public void attributeRemoved(HttpSessionBindingEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void attributeReplaced(HttpSessionBindingEvent arg0) {
// TODO Auto-generated method stub
}
//context删除时激发
@Override
public void contextDestroyed(ServletContextEvent arg0) {
// TODO Auto-generated method stub
}
//初始化时激发
@Override
public void contextInitialized(ServletContextEvent sce) {
//容器初始化时,向application中存放一个容器
this.application=sce.getServletContext();
this.application.setAttribute("alluser", new ArrayList());
}
@Override
public void sessionCreated(HttpSessionEvent se) {
// TODO Auto-generated method stub
}
@Override
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);
}
}
2)创建一个online.jsp
<%@page contentType="text/html"% import="java.util.*">
<%@page pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<div id="one">
<div id="two">
<h3>欢迎登录</h3>
<form action="online.jsp" method="post">
用户名:<input type="text" name="name" style="width: 110px;" />
<br />
密 码:<input type="password" name="password" style="width: 110px;" />
<br />
<br />
<input type="submit" name="commit" value="登录" style="color: blueviolet;" />
<a href="logout.jsp">注销</a>
</form>
</div>
<div id="three">
<!--向session接受输入的用户名-->
<%
request.setCharacterEncoding("UTF-8");
if(request.getParameter("name")!=null){
session.setAttribute("uname",request.getParameter("name"));
}
%>
<h2>在线人员</h2>
<%
List l=(List) application.getAttribute("alluser");
Iterator iter=l.Iterator();
while(iter.hasNext()){
%>
<li><%=iter.next()%></li>
<% } %>
<p>当前在线的用户数:<%=l.size() %></p>
</div>
</div>
</body>
</html>
3)创建logout.jsp页面实现用户注销
<body>
<%
sesion.invalidate()
%>
<a href="online.jsp">再次进入系统</a>
4)最后,在web.xml文件中配置监听
<listener>
<listener-class>xqyy.com.listener.OnLineCountListener</listener-class>
</listener>