java使用監(jiān)聽器實現(xiàn)一個統(tǒng)計網(wǎng)站在線人數(shù)的示例
本文主要介紹了java使用監(jiān)聽器實現(xiàn)一個統(tǒng)計網(wǎng)站在線人數(shù)的示例,具有一定的參考價值,有需要的朋友可以了解一下。
(1)創(chuàng)建一個監(jiān)聽器實現(xiàn)類
要大致統(tǒng)計一個網(wǎng)站的在線人數(shù),首先,可以通過ServletContextListener監(jiān)聽,當Web應(yīng)用上下文啟動時,在ServletContext中添加一個List,用來準備存放在線的用戶名;然后,可以通過HttpSessionAttributeListener監(jiān)聽,當用戶登錄成功把用戶名設(shè)置到Session中時同時將用戶名存放到ServletContext中的List列表中;最后通過HttpSessionListener監(jiān)聽,當用戶注銷會話時將用戶名從應(yīng)用上下文范圍中的List列表中刪除。
所以,編寫OnLineListener類實現(xiàn)ServletContextListener、HttpSessionAttributeListener、HttpSessionListener接口,具體代碼如下:
package com.web.servlet;
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;
//在線人數(shù)統(tǒng)計監(jiān)聽器實現(xiàn)類
public class OnlineListener implements ServletContextListener,
HttpSessionAttributeListener, HttpSessionListener {
private ServletContext application = null;
public void contextDestroyed(ServletContextEvent arg0) {
// TODO Auto-generated method stub
}
public void contextInitialized(ServletContextEvent arg0) {
//初始化一個application對象
this.application = arg0.getServletContext();
//設(shè)置一個列表屬性,用于保存在想用戶名
this.application.setAttribute("online", new LinkedList<String>());
}
//往會話中添加屬性時會回調(diào)的方法
public void attributeAdded(HttpSessionBindingEvent arg0) {
//取得用戶名列表
List<String> online = (List<String>) this.application
.getAttribute("online");
if ("username".equals(arg0.getName())) {
//將當前用戶名添加到列表中
online.add((String) arg0.getValue());
}
//將添加后的列表重新設(shè)置到application屬性中
this.application.setAttribute("online", online);
}
public void attributeRemoved(HttpSessionBindingEvent arg0) {
// TODO Auto-generated method stub
}
public void attributeReplaced(HttpSessionBindingEvent arg0) {
// TODO Auto-generated method stub
}
public void sessionCreated(HttpSessionEvent arg0) {
// TODO Auto-generated method stub
}
//會話銷毀時會回調(diào)的方法
public void sessionDestroyed(HttpSessionEvent arg0) {
//取得用戶名列表
List<String> online = (List<String>) this.application
.getAttribute("online");
//取得當前用戶名
String username = (String) arg0.getSession().getAttribute("username");
//將此用戶名從列表中刪除
online.remove(username);
//將刪除后的列表重新設(shè)置到application屬性中
this.application.setAttribute("online", online);
}
}
(2)在web.xml中注冊監(jiān)聽器
監(jiān)聽器實現(xiàn)好后,還需要在web.xml文件中進行注冊才能起作用,只需要在web.xml中像如下添加元素即可
<!-- 注冊一個監(jiān)聽器 --> <listener> <!-- 指定監(jiān)聽器實現(xiàn)類的全限定名 --> <listener-class> com.web.servlet.OnlineListener </listener-class> </listener
最后,我們創(chuàng)建幾個Servlet來測試這個監(jiān)聽器實現(xiàn)的功能。
處理用戶登錄的Servlet類代碼:
package com.web.servlet;
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;
//處理用戶登錄的Servlet
public class LoginServlet 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");//設(shè)置相應(yīng)內(nèi)容類型
String username= request.getParameter("username");//獲取請求參數(shù)中的用戶名
//往session中添加屬性,會觸發(fā)HttpSessionAttributeListener中的attributeAdded方法
if(username != null && !username.equals("")) {
request.getSession().setAttribute("username",username);
}
//從應(yīng)用上下文中獲取在線用戶名列表
List<String> online = (List<String>)getServletContext().getAttribute("online");
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
out.println("<HTML>");
out.println(" <HEAD><TITLE>用戶列表</TITLE></HEAD>");
out.println(" <BODY>");
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="/" mce_href="/""" + response.encodeURL("logout") + "/">注銷</a>");
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
}
}
處理用戶登錄Servlet的類代碼
package com.web.servlet;
import java.io.*;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.*;
//處理用戶注銷會話的Servlet
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");
//銷毀會話,會觸發(fā)SessionLinstener中的sessionDestroyed方法
request.getSession().invalidate();
//從應(yīng)用上下文中獲取在線用戶名列表
List<String> online = (List<String>)getServletContext().getAttribute("online");
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
out.println("<HTML>");
out.println(" <HEAD><TITLE>用戶列表</TITLE></HEAD>");
out.println(" <BODY>");
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="/" mce_href="/""index.html/">主頁</a>");
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
}
}
然后創(chuàng)建一個index.html文件,用來供用戶登錄,代碼如下:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <title>index.html</title> </head> <body> <form action = "login" method = "post"> 用戶名:<input type ="text" name = "username"/> <input type = "submit" value = "登錄"/><br/><br/> </form> </body> </html>
把WEB部署到Tomcat容器總,并啟動。打開瀏覽器訪問即可
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
IntelliJ IDEA 創(chuàng)建spring boot 的Hello World 項目(圖解)
這篇文章主要介紹了IntelliJ IDEA 創(chuàng)建spring boot 的Hello World 項目的步驟詳解,需要的朋友可以參考下2018-01-01
教你如何測試Spring Data JPA的Repository
Spring Data JPA 提供了一些便捷的方式來測試這種持久層的代碼,常見的兩種測試類型是集成測試和單元測試,本文通過示例代碼給大家介紹的非常詳細,感興趣的朋友跟隨小編一起看看吧2024-08-08
解決Springboot中@Async注解獲取不到上下文信息問題
實際開發(fā)中我們經(jīng)常需要通過spring上下文獲取一些配置信息,本文主要介紹了解決Springboot中@Async注解獲取不到上下文信息問題,具有一定的參考價值,感興趣的可以了解一下2024-01-01
MapStruct處理Java中實體與模型間不匹配屬性轉(zhuǎn)換的方法
今天小編就為大家分享一篇關(guān)于MapStruct處理Java中實體與模型間不匹配屬性轉(zhuǎn)換的方法,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧2019-03-03
Springboot+Redis實現(xiàn)API接口防刷限流的項目實踐
本文主要介紹了Springboot+Redis實現(xiàn)API接口防刷限流的項目實踐,通過限流可以讓系統(tǒng)維持在一個相對穩(wěn)定的狀態(tài),為更多的客戶提供服務(wù),具有一定的參考價值,感興趣的可以了解一下2024-07-07

