Java基于servlet监听器实现在线人数监控功能的方法

本文实例讲述了Java基于servlet监听器实现在线人数监控功能的方法。分享给大家供大家参考,具体如下:

1、分析:

做一个网站在线人数统计,可以通过ServletContextListener监听,当Web应用上下文启动时,在ServletContext中添加一个List.用来准备存放在线的用户名,然后通过HttpSessionAttributeListener监听,当用户登录成功,把用户名设置到Session中。同时将用户名方法到ServletContext的List中,最后通过HttpSessionListener监听,当用户注销会话时,讲用户名从应用上下文范围中的List列表中删除。

2、注意事项

测试时,需要启动不同的浏览器来登陆不同的用户,只有点击注销按钮才能减少在线用户,关闭浏览器不能减少在线用户。

3、项目源代码

(1)java代码

OnlineListener类

package com.smalle.listener;
import java.util.LinkedList;
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 OnlineListener implements
  ServletContextListener, HttpSessionAttributeListener, HttpSessionListener {
  private ServletContext application = null;
  //应用上下文初始时会回调的方法
  @Override
  public void contextInitialized(ServletContextEvent e) {
    //初始化一个application对象
    application = e.getServletContext();
    //设置一个列表属性,用于保存在线用户名
    this.application.setAttribute("online", new LinkedList<String>());
  }
  //往会话中添加属性时的回调方法
  @Override
  public void attributeAdded(HttpSessionBindingEvent e) {
    //取得用户名列表
    List<String> onlines = (List<String>) this.application.getAttribute("online");
    if("username".equals(e.getName())){
      onlines.add((String) e.getValue());
    }
    //将添加后的列表重新设置列application属性中.
    this.application.setAttribute("online", onlines);
  }
  //会话销毁时会回调的方法
  @Override
  public void sessionDestroyed(HttpSessionEvent e) {
    //取得用户名列表
    List<String> onlines = (List<String>) this.application.getAttribute("online");
    //取得当前用户名
    String username = (String) e.getSession().getAttribute("username");
    //将此用户从列表中删除
    onlines.remove(username);
    //讲删除后的列表重新设置到application属性中.
    this.application.setAttribute("online", onlines);
  }
  public void sessionCreated(HttpSessionEvent e) {}
  public void attributeRemoved(HttpSessionBindingEvent e) {}
  public void attributeReplaced(HttpSessionBindingEvent e) {}
  public void contextDestroyed(ServletContextEvent e) {}
}

LoginServlet类

package com.smalle.listener;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LoginServlet extends HttpServlet {
  private static final long serialVersionUID = 1L;
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    this.doPost(request, response);
  }
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    request.setCharacterEncoding("utf-8");  //设置响应内容类型
        String username= request.getParameter("username");  //获取请求参数中的用户名
        //往session中添加属性,会触发HttpSessionAttributeListener中的attributeAdded方法
        if(username != null && !username.equals("")) {
          request.getSession().setAttribute("username",username);
        }
        //从应用上下文中获取在线用户名列表
        List<String> online = (List<String>)getServletContext().getAttribute("online");
System.out.println("LoginServlet" + online);
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        out.println("");
        out.println(" <title>用户列表</title>");
        out.println(" ");
        out.println("当前用户是:" + username);
        out.print("  <hr><h3>在线用户列表</h3>");
        int size = online == null ? 0 : online.size();
        for (int i = 0; i < size; i++) {
          if(i > 0){
            out.println("<br>");
          }
          out.println(i + 1 + "." + online.get(i));
        }
        //注意: 要对链接URL进行自动重写处理
        out.println("<hr/><a href=\"" + response.encodeURL("logoutListener") + "\">注销</a>");
        out.println(" ");
        out.println("");
        out.flush();
        out.close();
  }
}

LogoutServlet类

package com.smalle.listener;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LogoutServlet extends HttpServlet{
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    this.doPost(request, response);
  }
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    request.setCharacterEncoding("utf-8");  //设置响应内容类型
    //销毁会话,会触发SessionLinstener中的sessionDestroyed方法
    request.getSession().invalidate();
    //从应用上下文中获取在线用户名列表
    List<String> online = (List<String>)getServletContext().getAttribute("online");
    response.setContentType("text/html;charset=utf-8");
    PrintWriter out = response.getWriter();
    out.println("");
    out.println(" <title>用户列表</title>");
    out.println(" ");
    out.print("  <h3>在线用户列表</h3>");
    int size = online == null ? 0 : online.size();
    for (int i = 0; i < size; i++) {
      if(i > 0){
        out.println("<br>");
      }
      out.println(i + 1 + "." + online.get(i));
    }
    out.println("<hr><a href='\'index.html\''>主页</a>");
    out.println(" ");
    out.println("");
    out.flush();
    out.close();
  }
}

(2)web.xml代码

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
 <display-name>testServlet</display-name>
  <listener>
    <listener-class>com.smalle.listener.OnlineListener</listener-class>
  </listener>
  <servlet>
    <servlet-name>LoginServlet</servlet-name>
    <servlet-class>com.smalle.listener.LoginServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>LoginServlet</servlet-name>
    <url-pattern>/loginListener</url-pattern>
  </servlet-mapping>
  <servlet>
    <servlet-name>LogoutServlet</servlet-name>
    <servlet-class>com.smalle.listener.LogoutServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>LogoutServlet</servlet-name>
    <url-pattern>/logoutListener</url-pattern>
  </servlet-mapping>
 <welcome-file-list>
  <welcome-file>index.jsp</welcome-file>
 </welcome-file-list>
</web-app>

(3)表现层代码

<!DOCTYPE html>
<html>
 <head>
  <title>index.html</title>
  <meta name="content-type" content="text/html; charset=UTF-8">
 </head>
 <body>
  <form action="loginListener" method="post">
    用户名:<input type="text" name="username">
  <input type="submit" value="登录"><br><br>
  </form>
 </body>
</html>

更多关于java算法相关内容感兴趣的读者可查看本站专题:《Java网络编程技巧总结》、《Java数据结构与算法教程》、《Java操作DOM节点技巧总结》、《Java文件与目录操作技巧汇总》和《Java缓存操作技巧汇总》

希望本文所述对大家java程序设计有所帮助。

声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:notice#cainiaojc.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。