1. Introduction to the listener
A listener is an ordinary Java program that implements a specific interface. This program is specially used to monitor another Java object. Method call or attribute change, when the above event occurs on the monitored object, a method of the listener will be executed immediately.
2. Types of Java listeners
(1)ServletContextListener
Used to listen to WEB, application startup and destruction events
public void contextInitialized( ServletContextEvent sce): Executed when initializing the web application
public void contextDestroyed(ServletContextEvent sce) {}: Executed when destroying the web application
(2)HttpSessionListener
is used Monitor the creation and destruction of Session objects
public void sessionCreated(HttpSessionEvent se) {}: Executed when the session is created
public void sessionDestroyed(HttpSessionEvent se) {}: Executed when the session is destroyed
(3)ServletRequestListener
Used to monitor the creation and destruction of Requset objects
public void requsetCreated(HttpSessionEvent se) {}:Executed when requset is created
public void requestDestroyed(HttpSessionEvent se) {}: Executed when requset is destroyed
(4)ServletContextAttributeListener
is used to monitor changes in WEB scope attributes, including: adding attributes, deleting attributes Attributes, modify attributes
attributeAdded(ServletContextEvent sce): Executed when adding attributes to ServletContext
attributeAdded(ServletContextRemoved sce): Executed when deleting attributes from ServletContext
attributeReplaced(ServletContextRemoved sce): Executed when modifying attributes in ServletContext
(5)HttpSessionAttributeListener
is used to monitor changes in Session scope attributes, including: adding attributes, deleting attributes, modifying attributes
(6)ServletRequestAttributeListener
is used to monitor changes in Requset scope attributes, including: adding attributes, deleting attributes, modifying attributes
(7)HttpSessionActivationListener
is used to listen Serialization and deserialization of an object in Session
3. Listener implements the function of counting people
(1) First create the listener package listener and then create a new OnlineListener class
package listener; import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.servlet.annotation.WebListener; import javax.servlet.http.HttpSessionAttributeListener; import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionListener; import javax.servlet.http.HttpSessionBindingEvent; @WebListener() public class OnlineListener implements ServletContextListener,HttpSessionListener, HttpSessionAttributeListener { private static int count=0; public OnlineListener() {//构造函数 } // ServletContextListener的实现方法,在初始化web应用时执行,你可以在此处初始化server上下文相关数据 public void contextInitialized(ServletContextEvent sce) {//应用初始化完成 } // ServletContextListener的实现方法,在web应用关闭时执行 public void contextDestroyed(ServletContextEvent sce) { } // HttpSessionListener的实现方法,session被创建的时候执行 public void sessionCreated(HttpSessionEvent se) {//创建 count++; ServletContext app = se.getSession().getServletContext(); app.setAttribute("count",count); } // HttpSessionListener的实现方法,session被销毁的时候执行 public void sessionDestroyed(HttpSessionEvent se) { count--; ServletContext app = se.getSession().getServletContext(); app.setAttribute("count",count); } }
(2) Create the interface of the listener servlet
import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; @WebServlet(name = "OnlineServlet",urlPatterns = "/online") public class OnlineServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String op=request.getParameter("op"); String result=""; switch (op){ case "login": //request.getSession()触发监听器的sessionCreated ServletContext app=request.getSession().getServletContext(); int count= (int) app.getAttribute("count"); result=String.format("当前%d人在线",count); break; case "logout": //销毁session,触发监听器的sessionDestroy request.getSession().invalidate();//销毁session result="您已经退出了!"; } response.setContentType("text/html;charset=utf-8"); PrintWriter out=response.getWriter(); out.write(result); out.close(); } }
4.Redis implements the function of counting people
Requirements: average access time, average number of people online at the same time, and the highest number of people online at the same time
(1) First design the data table:
Start accessing the page time, leave the page timetable: (id, place, ip, user_id, user_name, begin_time, end_time, env, info, len_min)
Statistical table: average visit duration, average number of people online at the same time, maximum number of people online at the same time (id, day, age_len_visit_min, acu, pcu)
Statistical record table: number of people online at the same time per minute. (id, min_time, num)
(2) Use redis to store the current online users. Each call can be regarded as browsing for one minute (it can be further refined according to the business, and only the scheduled task needs to record the last minute) and users in the current minute, you can calculate how often a user visits a certain page.
(3) At the same time, record the time when the user starts visiting the page and the time when he leaves the page, and you can analyze the follow-up.
(4) To facilitate data processing, the number of visits per page per minute can be recorded.
(5) redis, stores 2 hashes:
begin, timer The stored hash set records detailed information
now, the user access set passed by the interface, and records the refresh time
Update and refresh operations are performed through timers.
ps: Individual keys in the hash cannot be automatically set to expire, or you can use redis monitoring and use String type keys. Monitoring is filtering, and you can process what you need to process after matching it.
The above is the detailed content of How to implement the function of counting online people in Java. For more information, please follow other related articles on the PHP Chinese website!

Start Spring using IntelliJIDEAUltimate version...

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

Java...

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...


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

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.