servlet监听完成统计在线人数,显示在线人员列表(附源码)

ServletContext事件监听器---->针对applicationScope

 ServletContextListener(*)

对整个Web应用的装载和卸载进行监听。

 ServletContextAttributeListener

对ServletContext中的信息存放、删除和替换进行监听。

ServletContext就是Servlet上下文监听,在web中表示的是对启动服务和销毁服务进行监听,需要实现的接口:

ServletContextListener接口,实现的就是对上下午进行监听:

void contextInitialized(ServletContextEvent sce):启动上下文时的监听

void contextDestroyed(ServletContextEvent sce):销毁上下文时进行的监听

除了对上下文的启动和销毁进行监听的之外,还可以对上下文的属性进行监听:ServletContextAttributeListener接口。

void attributeAdded(ServletContextAttributeEvent event):设置上下文属性监听

void attributeRemoved(ServletContextAttributeEvent event):移除上下文属性的监听

void attributeReplaced(ServletContextAttributeEvent event):修改上下文属性的监听

ServletContextAttributeEvent:事件,可以通过事件取得属性的内容和名称。

·取得属性名称:public Java.lang.String getName()

·取得属性的值:public java.lang.Object getValue()

效果如下图:

当登录一个账号时

servlet监听完成统计在线人数,显示在线人员列表(附源码)

打开另一个浏览器,再登录一个账号

servlet监听完成统计在线人数,显示在线人员列表(附源码)

如上图,我们可以看到,程序已经完成了统计在线人数和显示人员列表的功能,那么他的实现流程是什么呢?

我们可以通过ServletContextListener完成在线人数的统计和显示在线人数列表,首先listener和filter一样要在web.xml中进行描述。

代码如下:

[html] view plain copy
 print?
  1. <listener>    
  2.         <listener-class>net.jvsun.ListenerTest</listener-class>    
  3.     </listener>  

为了测试这个程序,我们也必须完成用户登录功能。

数据库连接帮助类:

[java] view plain copy
 print?
  1. public class JDBCHelper {  
  2.     public static final String DRIVER = "oracle.jdbc.driver.OracleDriver";  
  3.     public static final String URL = "jdbc:oracle:thin:@localhost:1521:xxx";  
  4.     public static final String DBNAME = "scott";  
  5.     public static final String PASSWORD = "xxx";  
  6.     public static Connection getConn() throws Exception{  
  7.         Class.forName(DRIVER);  
  8.         Connection conn = DriverManager.getConnection(URL, DBNAME, PASSWORD);  
  9.         return conn;  
  10.     }  
  11. }  
用户实体类:

[java] view plain copy
 print?
  1. public class UserPOJO implements Serializable{  
  2.     private static final long serialVersionUID = 7554548269035753256L;  
  3.     private int id;  
  4.     private String username;  
  5.     private String password;  
  6.     public int getId() {  
  7.         return id;  
  8.     }  
  9.     public void setId(int id) {  
  10.         this.id = id;  
  11.     }  
  12.     public String getUsername() {  
  13.         return username;  
  14.     }  
  15.     public void setUsername(String username) {  
  16.         this.username = username;  
  17.     }  
  18.     public String getPassword() {  
  19.         return password;  
  20.     }  
  21.     public void setPassword(String password) {  
  22.         this.password = password;  
  23.     }  
  24.     public UserPOJO(int id, String username, String password) {  
  25.         super();  
  26.         this.id = id;  
  27.         this.username = username;  
  28.         this.password = password;  
  29.     }  
  30.     public UserPOJO(String username, String password) {  
  31.         this.username = username;  
  32.         this.password = password;  
  33.     }  
  34.     public UserPOJO() {  
  35.         super();  
  36.         // TODO Auto-generated constructor stub  
  37.     }  
  38.       
  39. }  

数据库处理类:

[java] view plain copy
 print?
  1. public class UserDAO {  
  2.     public UserPOJO login(String username, String password) {  
  3.         UserPOJO user=null;  
  4.         Connection conn = null;  
  5.         PreparedStatement pstate = null;  
  6.         ResultSet res = null;  
  7.         try {  
  8.             conn=JDBCHelper.getConn();  
  9.             String sql="select id,username from userinfo where username=? and password=?";  
  10.             pstate = conn.prepareStatement(sql);  
  11.             pstate.setString(1, username);  
  12.             pstate.setString(2, password);  
  13.             res = pstate.executeQuery();  
  14.             while(res.next()){  
  15.                 user=new UserPOJO(res.getInt(1),username,null);  
  16.             }  
  17.         } catch (Exception e) {  
  18.             e.printStackTrace();  
  19.         }finally{  
  20.             try {  
  21.                 res.close();  
  22.                 pstate.close();  
  23.                 conn.close();  
  24.             } catch (SQLException e) {  
  25.                 e.printStackTrace();  
  26.             }  
  27.               
  28.         }  
  29.         return user;  
  30.     }  
  31. }  


servlet类:

[java] view plain copy
 print?
  1. public class UserServlet extends HttpServlet{  
  2.   
  3.     @Override  
  4.     protected void doGet(HttpServletRequest request, HttpServletResponse response)  
  5.             throws ServletException, IOException {  
  6.         String path = request.getContextPath();  
  7.         response.setContentType("text/html; charset=utf-8");  
  8.         request.setCharacterEncoding("utf-8");  
  9.         String username = request.getParameter("username");  
  10.         String password = request.getParameter("password");  
  11.         ServletContext application = this.getServletContext();//取得application对象  
  12.         List<String> list = (List<String>) application.getAttribute("allUser");  
  13.         if(list.indexOf(username) == -1){  
  14.             UserPOJO pojo = new UserDAO().login(username, password);  
  15.             if(null != pojo){  
  16.                 HttpSession session = request.getSession(true);//取得session对象  
  17.                 session.setAttribute("userName", username);  
  18.             }  
  19.               
  20.         }  
  21.         response.sendRedirect(path+"/index.jsp");  
  22.     }  
  23.   
  24.     @Override  
  25.     protected void doPost(HttpServletRequest req, HttpServletResponse resp)  
  26.             throws ServletException, IOException {  
  27.         doGet(req, resp);  
  28.     }  
  29.   
  30. }  


监听类:

[java] view plain copy
 print?
  1. public class ListenerTest implements ServletContextListener,HttpSessionAttributeListener,HttpSessionListener{  
  2.     ServletContext application = null;  
  3.     public void contextDestroyed(ServletContextEvent event) {  
  4.         System.out.println("服务器关闭");  
  5.     }  
  6.   
  7.     public void contextInitialized(ServletContextEvent event) {  
  8.         List<String> list = new ArrayList<String>();  
  9.         //用来保存所有已登录的用户  
  10.         application =  event.getServletContext();  
  11.         //取得application对象  
  12.         application.setAttribute("allUser", list);  
  13.         //将集合设置到application范围属性中去  
  14.           
  15.     }  
  16.   
  17.     public void attributeAdded(HttpSessionBindingEvent se) {  
  18.         List<String> list = (List<String>)application.getAttribute("allUser");  
  19.         //假设:用户登陆成功之后,只将户名设置到session中  
  20.         String userName = (String)se.getValue();  
  21.         //取得用户名  
  22.         if(list.indexOf(userName) == -1){  
  23.             //表示此用户之前没有登陆  
  24.             list.add(userName);  
  25.             application.setAttribute("allUser", list);  
  26.         }  
  27.     }  
  28.   
  29.     public void attributeRemoved(HttpSessionBindingEvent se) {  
  30.         List<String> list = (List<String>)application.getAttribute("allUser");  
  31.         list.remove((String)se.getValue());  
  32.         application.setAttribute("allUser", list);  
  33.     }  
  34.   
  35.     public void attributeReplaced(HttpSessionBindingEvent se) {  
  36.           
  37.     }  
  38.   
  39.     public void sessionCreated(HttpSessionEvent event) {  
  40.           
  41.     }  
  42.   
  43.     public void sessionDestroyed(HttpSessionEvent event) {  
  44.           
  45.     }  
  46. }  


登录页面

[java] view plain copy
 print?
  1. <%@page contentType="text/html; charset=utf-8"%>  
  2. <%@page import="java.util.*" %>  
  3. <%  
  4.     String path  = request.getContextPath();  
  5.  %>  
  6.    
  7. <html>  
  8.     <body>  
  9.       
  10.         <form action="<%=path %>/Login" method="post">  
  11.             账号:  
  12.             <input type="text" name="username" />  
  13.             <br />  
  14.             密码:  
  15.             <input type="password" name="password" />  
  16.             <br />  
  17.             <input type="submit" value="提交" />  
  18.         </form>  
  19.   
  20.     </body>  
  21.       
  22. </html>  

显示在线人数和在线人员的列表界面

[java] view plain copy
 print?
  1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  
  2. <%  
  3. String path = request.getContextPath();  
  4. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
  5. %>  
  6.   
  7. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  8. <html>  
  9.   <head>  
  10.     <base href="<%=basePath%>">   
  11.     <title></title>  
  12.   </head>  
  13.     
  14.   <body>  
  15.     <ul>  
  16.     <%  
  17.         System.out.println(application.getAttribute("allUser"));  
  18.         if(null != application.getAttribute("allUser")){  
  19.             List<String> list = (List<String>)application.getAttribute("allUser");  
  20.             %>  
  21.             <h2>在线人数:<%=list.size() %></h2>  
  22.             <%  
  23.             for(String s:list){  
  24.             %>  
  25.             <a>姓名:</a><%=s %><a>---->此时在线</a><br>  
  26.               
  27.             <%  
  28.             }  
  29.         }  
  30.      %>  
  31.      </ul>  
  32.     <hr/>  
  33.     <a href="<%=path %>/logout.jsp">注销</a>  
  34.   </body>  
  35. </html>  

注销界面:

[java] view plain copy
 print?
  1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  
  2. <%  
  3. String path = request.getContextPath();  
  4. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
  5. %>  
  6.   
  7. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  8. <html>  
  9.   <head>  
  10.     <base href="<%=basePath%>">  
  11.     <title>logout</title>  
  12.   </head>  
  13.   <body>  
  14.     <%  
  15.         session.removeAttribute("username");  
  16.         session.invalidate();  
  17.         response.sendRedirect("login.jsp");  
  18.     %>  
  19.   </body>  
  20. </html>  

代码下载地址:http://download.****.net/detail/weixin_36380516/9811993