This article describes the method of Java implementing online user monitoring function based on servlet listener. Share it for your reference, as follows:
1. Analysis:
To do a website's online number of people, you can listen through the ServletContextListener. When the web application context is started, add a List in the ServletContext. Use it to prepare the username stored online, and then listen through the HttpSessionAttributeListener. When the user logs in successfully, set the username to the Session. At the same time, the user name method is placed into the List of ServletContext, and finally listened through the HttpSessionListener. When the user logs out of the session, the user name is deleted from the List list in the application context scope.
2. Things to note
During testing, you need to start different browsers to log in to different users. Only by clicking the logout button can you reduce online users. Close the browser cannot reduce online users.
3. Project source code
(1) Java code
OnlineListener class
package com.smalle.listener;import java.util.LinkedList;import java.util.List;import javax.servlet.ServletContext;import javax.servlet.ServletContextEvent;import javax.servlet.ServletContextListener;import javax.servlet.http.HttpSessionAttributeListener;import javax.servlet.http.HttpSessionBindingEvent;import javax.servlet.http.HttpSessionEvent;import javax.servlet.http.HttpSessionListener;public class OnlineListener implements ServletContextListener, HttpSessionAttributeListener, HttpSessionListener { private ServletContext application = null; //Methods that callbacks at the beginning of the application context @Override public void contextInitialized(ServletContextEvent e) { //Initialize an application object application = e.getServletContext(); //Set a list attribute to save the online username this.application.setAttribute("online", new LinkedList<String>()); } //Callback method when adding attributes to the session @Override public void attributeAdded(HttpSessionBindingEvent e) { //Get the username list List<String> onlines = (List<String>) this.application.getAttribute("online"); if("username".equals(e.getName())){ onlines.add((String) e.getValue()); } //Reset the column application property of the added list. this.application.setAttribute("online", onlines); } //Methods that callbacks when the session is destroyed @Override public void sessionDestroyed(HttpSessionEvent e) { //Get the username list List<String> onlines = (List<String>) this.application.getAttribute("online"); //Get the current username String username = (String) e.getSession().getAttribute("username"); //Delete this user from the list onlines.remove(username); //Reset the deleted list into the application property. this.application.setAttribute("online", onlines); } public void sessionCreated(HttpSessionEvent e) {} public void attributeRemoved(HttpSessionBindingEvent e) {} public void attributeReplaced(HttpSessionBindingEvent e) {}}LoginServlet class
package com.smalle.listener;import java.io.IOException;import java.io.PrintWriter;import java.util.List;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class LoginServlet extends HttpServlet { private static final long serialVersionUID = 1L; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); //Set the response content type String username= request.getParameter("username"); //Get the user name in the request parameter//Add attributes to the session will trigger the attributeAdded method in the HttpSessionAttributeListener if(username != null && !username.equals("")) { request.getSession().setAttribute("username",username); } //Get the online username list from the application context List<String> online = (List<String>)getServletContext().getAttribute("online"); System.out.println("LoginServlet" + online); response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); out.println(""); out.println(" <title>user list</title>"); out.println(" "); out.println(" Current user is: " + username); out.print(" <hr><h3>online user list</h3>"); int size = online == null ? 0 : online.size(); for (int i = 0; i < size; i++) { if(i > 0){ out.println("<br>"); } out.println(i + 1 + "." + online.get(i)); } //Note: To automatically rewrite the link URL out.println("<hr/><a href=/"" + response.encodeURL("logoutListener") + "/">Logout</a>"); out.println("); out.println(""); out.flush(); out.close(); }}LogoutServlet class
package com.smalle.listener;import java.io.IOException;import java.io.PrintWriter;import java.util.List;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class LogoutServlet extends HttpServlet{ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); //Set the response content type//Destroy the session, the sessionDestroyed method in the SessionLinstener will be triggered to request.getSession().invalidate(); //Get the online username list from the application context List<String> online = (List<String>)getServletContext().getAttribute("online"); response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); out.println(""); out.println(" <title>User List</title>"); out.println(""); out.println(" "); out.print(" <h3>Online User List</h3>"); int size = online == null ? 0 : online.size(); for (int i = 0; i < size; i++) { if(i > 0){ out.println("<br>"); } out.println(i + 1 + "." + online.get(i)); } out.println("<hr><a href='/'index.html/''>Home</a>"); out.println(" "); out.println(""); out.flush(); out.close(); }}(2) web.xml code
<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>testServlet</display-name> <listener> <listener-class>com.smalle.listener.OnlineListener</listener-class> </listener> <servlet> <servlet-name>LoginServlet</servlet-name> <servlet-class>com.smalle.listener.LoginServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>LoginServlet</servlet-name> <url-pattern>/loginListener</url-pattern> </servlet-mapping> <servlet> <servlet-name>LogoutServlet</servlet-name> <servlet-class>com.smalle.listener.LogoutServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>LogoutServlet</servlet-name> <url-pattern>/logoutListener</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list></web-app>
(3) Presentation layer code
<!DOCTYPE html><html> <head> <title>index.html</title> <meta name="content-type" content="text/html; charset=UTF-8"> </head> <body> <form action="loginListener" method="post"> Username: <input type="text" name="username"> <input type="submit" value="Login"><br><br> </form> </body></html>
For more information about Java algorithms, readers who are interested in this site can view the topics: "Summary of Java Network Programming Skills", "Tutorials on Java Data Structures and Algorithms", "Summary of Java Operation DOM Node Skills", "Summary of Java File and Directory Operation Skills" and "Summary of Java Cache Operation Skills"
I hope this article will be helpful to everyone's Java programming.