How to implement the function of counting online people in Java
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!

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



Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.
