Java基于servlet監(jiān)聽器實現(xiàn)在線人數(shù)監(jiān)控功能的方法

本文實例講述了Java基于servlet監(jiān)聽器實現(xiàn)在線人數(shù)監(jiān)控功能的方法。分享給大家供大家參考,具體如下:

成都創(chuàng)新互聯(lián)"三網(wǎng)合一"的企業(yè)建站思路。企業(yè)可建設擁有電腦版、微信版、手機版的企業(yè)網(wǎng)站。實現(xiàn)跨屏營銷,產(chǎn)品發(fā)布一步更新,電腦網(wǎng)絡+移動網(wǎng)絡一網(wǎng)打盡,滿足企業(yè)的營銷需求!成都創(chuàng)新互聯(lián)具備承接各種類型的做網(wǎng)站、成都網(wǎng)站建設項目的能力。經(jīng)過十載的努力的開拓,為不同行業(yè)的企事業(yè)單位提供了優(yōu)質(zhì)的服務,并獲得了客戶的一致好評。

1、分析:

做一個網(wǎng)站在線人數(shù)統(tǒng)計,可以通過ServletContextListener監(jiān)聽,當Web應用上下文啟動時,在ServletContext中添加一個List.用來準備存放在線的用戶名,然后通過HttpSessionAttributeListener監(jiān)聽,當用戶登錄成功,把用戶名設置到Session中。同時將用戶名方法到ServletContext的List中,最后通過HttpSessionListener監(jiān)聽,當用戶注銷會話時,講用戶名從應用上下文范圍中的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;
  //應用上下文初始時會回調(diào)的方法
  @Override
  public void contextInitialized(ServletContextEvent e) {
    //初始化一個application對象
    application = e.getServletContext();
    //設置一個列表屬性,用于保存在線用戶名
    this.application.setAttribute("online", new LinkedList<String>());
  }
  //往會話中添加屬性時的回調(diào)方法
  @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);
  }
  //會話銷毀時會回調(diào)的方法
  @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");  //設置響應內(nèi)容類型
        String username= request.getParameter("username");  //獲取請求參數(shù)中的用戶名
        //往session中添加屬性,會觸發(fā)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><h4>在線用戶列表</h4>");
        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");  //設置響應內(nèi)容類型
    //銷毀會話,會觸發(fā)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("  <h4>在線用戶列表</h4>");
    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)表現(xiàn)層代碼

<!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算法相關內(nèi)容感興趣的讀者可查看本站專題:《Java網(wǎng)絡編程技巧總結》、《Java數(shù)據(jù)結構與算法教程》、《Java操作DOM節(jié)點技巧總結》、《Java文件與目錄操作技巧匯總》和《Java緩存操作技巧匯總》

希望本文所述對大家java程序設計有所幫助。

標題名稱:Java基于servlet監(jiān)聽器實現(xiàn)在線人數(shù)監(jiān)控功能的方法
本文鏈接:http://muchs.cn/article28/ghiccp.html

成都網(wǎng)站建設公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站內(nèi)鏈、軟件開發(fā)網(wǎng)站設計公司、自適應網(wǎng)站、微信公眾號、網(wǎng)站策劃

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

微信小程序開發(fā)