First of all, this statistics has a flaw in the number of people online. One person can have multiple sessions at the same time, resulting in certain inaccurate statistics.
Next, start writing the code.
Step 1: Implement the method in HttpSessionListener, add the annotation @WebListener
@WebListener public class SessionListener implements HttpSessionListener{ public void sessionCreated(HttpSessionEvent arg0) { // TODO Auto-generated method stub ServletContext context = arg0.getSession().getServletContext(); if (context.getAttribute("count")==null) { context.setAttribute("count", 0); }else { int count = (Integer) context.getAttribute("count"); context.setAttribute("count", count+1); } } public void sessionDestroyed(HttpSessionEvent arg0) { // TODO Auto-generated method stub ServletContext context = arg0.getSession().getServletContext(); if (context.getAttribute("count")==null) { context.setAttribute("count", 0); }else { int count = (Integer) context.getAttribute("count"); if (count<1) { count = 1; } context.setAttribute("count", count-1); } HttpSession session = arg0.getSession(); String name = (String) session.getAttribute("name"); HashSet<String> nameSet = (HashSet<String>) context.getAttribute("nameSet"); nameSet.remove(name); } }Step 2: Control the creation of session and put it into the object
HttpSession session = request.getSession(); session.setAttribute("name", name); Object count = context.getAttribute("count"); if (count==null) { count = 0; }Step 3: Start the class with the annotation @ServletComponentScan, so that you can scan to the listener
Note, this code is suitable for spring-boot development
Simply put, add a listener in javaWeb to web.xml
<listener> <listener-class>zjq.listener.SessionListener</listener-class> </listener>
Summarize
The above is the implementation code for Spring boot to count the number of online users through the HttpSessionListener monitor that the editor introduced to you. I hope it will be helpful to everyone. If you have any questions, please leave me a message and the editor will reply to everyone in time. Thank you very much for your support to Wulin.com website!