Example of using Listener to implement global statistics on the website
1. Website global statistical variable class, only define global variables


1 package com.lt.listener; 2 3 import java.util.Date; 4 import java.util.HashMap; 5 import java.util.Map; 6 7 import javax.servlet.http.HttpSession; 8 /** 9 * 网站全局变量类10 * @author LIUTIE11 *12 */13 public abstract class ApplicationConstants {14 15 /**16 * 用户登录session名称17 */18 public static final String LOGIN_SESSION_NAME = "userInfo";19 20 /**21 * 索引所有的session 22 * 用于单一登录23 */24 public static Map<String,HttpSession> SESSION_MAP = new HashMap<>();25 26 /**27 * 当前在线用户数28 */29 public static int CURRENT_LOGIN_COUNT = 0;30 31 /**32 * 历史访客总数33 */34 public static int TOTAL_HISTORY_COUNT = 0;35 36 /**37 * 最高同时在线人数38 */39 public static int MAX_ONLINE_COUNT = 0;40 41 /**42 * 服务器启动时间43 */44 public static Date SERVER_START_DATE = new Date();45 46 /**47 * 最高在线人数时间48 */49 public static Date MAX_ONLINE_COUNT_DATE = new Date();50 51 52 53 }
2. Implement servletContext monitoring to record server information


1 package com.lt.listener; 2 3 import java.util.Date; 4 5 import javax.servlet.ServletContextEvent; 6 import javax.servlet.ServletContextListener; 7 8 /** 9 * servletContext监听10 * 记录服务器信息 启动关闭时间等11 * @author LIUTIE12 *13 */14 public class MyContextListener implements ServletContextListener {15 16 /**17 * 服务器启动时被调用18 */19 @Override20 public void contextDestroyed(ServletContextEvent arg0) {21 //记录启动时间22 ApplicationConstants.SERVER_START_DATE = new Date();23 }24 25 /**26 * 服务器关闭时被调用27 */28 @Override29 public void contextInitialized(ServletContextEvent arg0) {30 //保存数据到硬盘31 // TODO Auto-generated method stub32 }33 34 }
3. Implement HttpSessionListener, HttpSessionAttributeListener monitoring, which is used to record login information, total number of visitors, number of people online, and realize single login, etc.


1 package com.lt.listener; 2 3 import java.util.Date; 4 5 import javax.servlet.http.HttpSession; 6 import javax.servlet.http.HttpSessionAttributeListener; 7 import javax.servlet.http.HttpSessionBindingEvent; 8 import javax.servlet.http.HttpSessionEvent; 9 import javax.servlet.http.HttpSessionListener; 10 11 /** 12 * session监听 13 * 记录登录信息 访问总人数 在线人数等 14 * 实现单一登录 15 * @author LIUTIE 16 * 17 */ 18 public class MySessionListener implements HttpSessionListener, HttpSessionAttributeListener { 19 20 /** 21 * session创建时被调用 22 */ 23 @Override 24 public void sessionCreated(HttpSessionEvent sessionEvent) { 25 // 获取创建的session 26 HttpSession session = sessionEvent.getSession(); 27 // 添加到map 28 ApplicationConstants.SESSION_MAP.put(session.getId(), session); 29 // 访问总人数++ 30 ApplicationConstants.TOTAL_HISTORY_COUNT++; 31 // 如果map总数大于最高同时在线人数则更新最高在线人数及时间 32 if (ApplicationConstants.MAX_ONLINE_COUNT < ApplicationConstants.SESSION_MAP.size()) { 33 ApplicationConstants.MAX_ONLINE_COUNT = ApplicationConstants.SESSION_MAP.size(); 34 ApplicationConstants.MAX_ONLINE_COUNT_DATE = new Date(); 35 } 36 37 } 38 39 /** 40 * session销毁时被调用 41 */ 42 @Override 43 public void sessionDestroyed(HttpSessionEvent sessionEvent) { 44 // 获取即将被销毁的session 45 HttpSession session = sessionEvent.getSession(); 46 // 在map中根据key移除 47 ApplicationConstants.SESSION_MAP.remove(session.getId()); 48 } 49 50 /** 51 * 添加session属性时被调用 52 */ 53 @Override 54 public void attributeAdded(HttpSessionBindingEvent event) { 55 // 判断是否添加的用户登录信息session 56 if (event.getName().equals(ApplicationConstants.LOGIN_SESSION_NAME)) { 57 // 当前登录用户数++ 58 ApplicationConstants.CURRENT_LOGIN_COUNT++; 59 // 是否在其他机器登录处理 60 isLoginInOtherPlace(event); 61 } 62 } 63 64 /** 65 * 移除session属性时被调用 66 */ 67 @Override 68 public void attributeRemoved(HttpSessionBindingEvent event) { 69 // 判断是否移除的用户登录信息session 70 if (event.getName().equals(ApplicationConstants.LOGIN_SESSION_NAME)) { 71 // 当前登录用户数-- 72 ApplicationConstants.CURRENT_LOGIN_COUNT--; 73 // 是否在其他机器登录处理 74 isLoginInOtherPlace(event); 75 } 76 } 77 78 /** 79 * 修改session属性时被调用 80 */ 81 @Override 82 public void attributeReplaced(HttpSessionBindingEvent event) { 83 84 // 判断是否修改的用户登录信息session 85 if (event.getName().equals(ApplicationConstants.LOGIN_SESSION_NAME)) { 86 // 是否在其他机器登录处理 87 isLoginInOtherPlace(event); 88 } 89 } 90 91 /** 92 * 是否在其他机器登录处理 93 * 94 * @param event 95 */ 96 private void isLoginInOtherPlace(HttpSessionBindingEvent event) { 97 // 获取添加的session 98 HttpSession session = event.getSession(); 99 // 遍历查找此用户是否登录100 for (HttpSession s : ApplicationConstants.SESSION_MAP.values()) {101 // 如果已经在其他机器登录则使其失效102 if (event.getValue().equals(s.getAttribute(ApplicationConstants.LOGIN_SESSION_NAME))103 && session.getId() != s.getId()) {104 // 使session失效105 session.invalidate();106 break;107 }108 }109 }110 }
4. Implement request monitoring to record customer information ip, url, etc.


1 package com.lt.listener; 2 3 import javax.servlet.ServletRequestEvent; 4 import javax.servlet.ServletRequestListener; 5 import javax.servlet.http.HttpServletRequest; 6 7 /** 8 * request监听 用于记录客户信息 ip、url等 9 * 10 * @author LIUTIE11 *12 */13 public class MyRequestListener implements ServletRequestListener {14 15 /**16 * request销毁时调用17 */18 @Override19 public void requestDestroyed(ServletRequestEvent event) {20 // TODO Auto-generated method stub21 22 }23 24 /**25 * request创建时调用26 */27 @Override28 public void requestInitialized(ServletRequestEvent event) {29 HttpServletRequest request = (HttpServletRequest) event;30 // 客户端ip31 String ip = request.getRemoteAddr();32 // 访问的URL地址33 String url = request.getRequestURI();34 // 只做简单后台打印35 System.out.println("The client ip is " + ip);36 System.out.println("The address url is " + url);37 }38 39 }


<listener><listener-class>com.lt.listener.MyContextListener</listener-class></listener><listener><listener-class>com.lt.listener.MySessionListener</listener-class></listener><listener><listener-class>com.lt.listener.MyRequestListener</listener-class></listener>
The above is the detailed content of Example of using Listener to implement global statistics on the website. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



How to implement dual WeChat login on Huawei mobile phones? With the rise of social media, WeChat has become one of the indispensable communication tools in people's daily lives. However, many people may encounter a problem: logging into multiple WeChat accounts at the same time on the same mobile phone. For Huawei mobile phone users, it is not difficult to achieve dual WeChat login. This article will introduce how to achieve dual WeChat login on Huawei mobile phones. First of all, the EMUI system that comes with Huawei mobile phones provides a very convenient function - dual application opening. Through the application dual opening function, users can simultaneously

The programming language PHP is a powerful tool for web development, capable of supporting a variety of different programming logics and algorithms. Among them, implementing the Fibonacci sequence is a common and classic programming problem. In this article, we will introduce how to use the PHP programming language to implement the Fibonacci sequence, and attach specific code examples. The Fibonacci sequence is a mathematical sequence defined as follows: the first and second elements of the sequence are 1, and starting from the third element, the value of each element is equal to the sum of the previous two elements. The first few elements of the sequence

How to implement the WeChat clone function on Huawei mobile phones With the popularity of social software and people's increasing emphasis on privacy and security, the WeChat clone function has gradually become the focus of people's attention. The WeChat clone function can help users log in to multiple WeChat accounts on the same mobile phone at the same time, making it easier to manage and use. It is not difficult to implement the WeChat clone function on Huawei mobile phones. You only need to follow the following steps. Step 1: Make sure that the mobile phone system version and WeChat version meet the requirements. First, make sure that your Huawei mobile phone system version has been updated to the latest version, as well as the WeChat App.

In today's software development field, Golang (Go language), as an efficient, concise and highly concurrency programming language, is increasingly favored by developers. Its rich standard library and efficient concurrency features make it a high-profile choice in the field of game development. This article will explore how to use Golang for game development and demonstrate its powerful possibilities through specific code examples. 1. Golang’s advantages in game development. As a statically typed language, Golang is used in building large-scale game systems.

Implementing exact division operations in Golang is a common need, especially in scenarios involving financial calculations or other scenarios that require high-precision calculations. Golang's built-in division operator "/" is calculated for floating point numbers, and sometimes there is a problem of precision loss. In order to solve this problem, we can use third-party libraries or custom functions to implement exact division operations. A common approach is to use the Rat type from the math/big package, which provides a representation of fractions and can be used to implement exact division operations.

PHP Game Requirements Implementation Guide With the popularity and development of the Internet, the web game market is becoming more and more popular. Many developers hope to use the PHP language to develop their own web games, and implementing game requirements is a key step. This article will introduce how to use PHP language to implement common game requirements and provide specific code examples. 1. Create game characters In web games, game characters are a very important element. We need to define the attributes of the game character, such as name, level, experience value, etc., and provide methods to operate these

As a world-renowned short video social platform, Douyin has won the favor of a large number of users with its unique personalized recommendation algorithm. This article will delve into the value and principles of Douyin video recommendation to help readers better understand and make full use of this feature. 1. What is Douyin recommended video? Douyin recommended video uses intelligent recommendation algorithms to filter and push personalized video content to users based on their interests and behavioral habits. The Douyin platform analyzes users' viewing history, like and comment behavior, sharing records and other data to select and recommend videos that best suit users' tastes from a huge video library. This personalized recommendation system not only improves user experience, but also helps users discover more video content that matches their preferences, thereby enhancing user stickiness and retention rate. at this

I'm really sorry that I can't provide real-time programming guidance, but I can provide you with a code example to give you a better understanding of how to use PHP to implement SaaS. The following is an article within 1,500 words, titled "Using PHP to implement SaaS: A comprehensive analysis." In today's information age, SaaS (Software as a Service) has become the mainstream way for enterprises and individuals to use software. It provides a more flexible and convenient way to access software. With SaaS, users don’t need to be on-premises
