欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2023-12-20 08:23:28
本文实例讲述了java基于servlet监听器实现在线人数监控功能的方法。分享给大家供大家参考,具体如下: 1、分析: 做一个网站在线人数统计,可以通过servletc...

本文实例讲述了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程序设计有所帮助。

上一篇:

下一篇: