search
HomeJavajavaTutorialExample 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> 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 }</string>
View Code

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 }
View Code

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 
View Code

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 }
View Code
5. Configure a line of listener in web.xml

        <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>
View Code
Listener Category:

1. Listener that monitors the creation and destruction of objects:

HttpSessionListener: sessionCreated(HttpSessionEvent sessionEvent), sessionDestroyed(HttpSessionEvent sessionEvent)

ServletRequestListener: requestInitialized(ServletRequestEvent event ), requestDestroyed(ServletRequestEvent event)

ServletContextListener: contextInitialized(ServletContextEvent event), contextDestroyed(ServletContextEvent event)

2. Listener that listens for changes in the properties of the object:

HttpSessionAttributeListener: (Triggered when adding, updating, or removing a session)

attributeAdded(HttpSessionBindingEvent event), attributeReplaced(HttpSessionBindingEvent event), attributeRemoved(HttpSessionBindingEvent event)

ServletContextAttributeListener: (add, update, remove context Triggered when)

attributeAdded(ServletContextAttributeEvent event), attributeReplaced(ServletContextAttributeEvent event), attributeRemoved(ServletContextAttributeEvent event)

ServletRequestAttributeListener: (triggered when adding, updating, or removing a request)

AttributeAdded(ServletRequestAttributeEvent event), attributeReplaced(ServletRequestAttributeEvent event), attributeRemoved(ServletRequestAttributeEvent event)

3. Monitor objects in Session

HttpSessionBindingListener: (Object is put into session, object is removed from session Triggered when)

ValueBound(HttpSessionBindingEvent event), valueUnbound(HttpSessionBindingEvent event)

HttpSessionActivationListener: (Triggered when the object in the session is passivated or the object is reloaded ps: the content in the session The process of saving to the hard disk is called passivation. Passivation requires the implementation of Serializable serialization interface)

sessionWillPassivate(HttpSessionEvent event), sessionDidActivate(HttpSessionEvent event)

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!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Why can't the main class be found after copying and pasting the package in IDEA? Is there any solution?Why can't the main class be found after copying and pasting the package in IDEA? Is there any solution?Apr 19, 2025 pm 07:57 PM

Why can't the main class be found after copying and pasting the package in IDEA? Using IntelliJIDEA...

Java multi-interface call: How to ensure that interface A is executed before interface B is executed?Java multi-interface call: How to ensure that interface A is executed before interface B is executed?Apr 19, 2025 pm 07:54 PM

State synchronization between Java multi-interface calls: How to ensure that interface A is called after it is executed? In Java development, you often encounter multiple calls...

In Java programming, how to stop subsequent code execution when student ID is repeated?In Java programming, how to stop subsequent code execution when student ID is repeated?Apr 19, 2025 pm 07:51 PM

How to stop subsequent code execution when ID is repeated in Java programming. When learning Java programming, you often encounter such a requirement: when a certain condition is met,...

Ultimate consistency: What business scenarios are applicable to? How to ensure the consistency of the final data?Ultimate consistency: What business scenarios are applicable to? How to ensure the consistency of the final data?Apr 19, 2025 pm 07:48 PM

In-depth discussion of final consistency: In the distributed system of application scenarios and implementation methods, ensuring data consistency has always been a major challenge for developers. This article...

After the Spring Boot service is running for a period of time, how to troubleshoot?After the Spring Boot service is running for a period of time, how to troubleshoot?Apr 19, 2025 pm 07:45 PM

The troubleshooting idea of ​​SSH connection failure after SpringBoot service has been running for a period of time has recently encountered a problem: a Spring...

How to push the video stream of Hikvision camera SDK to the front-end Vue project for real-time playback?How to push the video stream of Hikvision camera SDK to the front-end Vue project for real-time playback?Apr 19, 2025 pm 07:42 PM

How to push video streams from Hikvision camera SDK to front-end Vue project? During the development process, you often encounter videos that need to be captured by the camera to be circulated...

How to limit access to access_token via OAuth2.0 scope parameter?How to limit access to access_token via OAuth2.0 scope parameter?Apr 19, 2025 pm 07:39 PM

How to use access_token of OAuth2.0 to restrict interface access permissions How to ensure access_token when authorizing using OAuth2.0...

In Spring Boot Redis, how to solve the problem of returning garbled codes?In Spring Boot Redis, how to solve the problem of returning garbled codes?Apr 19, 2025 pm 07:36 PM

SpringBootRedis gets the key garbled problem analysis using Spring...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.