java USES listeners to implement an example of counting the number of people on a website

  • 2020-05-10 18:15:05
  • OfStack

This paper mainly introduces the example of java using listener to realize the online number of people on a website, which has a definite reference value and can be understood by friends in need.

(1) create a listener implementation class

To roughly count the number of people online on a website, first of all, you can listen through ServletContextListener. When the application context of Web is launched, you can add an List in ServletContext to prepare to store the online user name. Then, you can listen through HttpSessionAttributeListener and store the user name in List list in ServletContext when the user has successfully logged in and set the user name to Session. Finally, by listening through HttpSessionListener, the user name is removed from the List list in the application context scope when the user logs out of the session.

Therefore, write OnLineListener class to implement ServletContextListener, HttpSessionAttributeListener and HttpSessionListener interfaces. The specific code is as follows:


package com.web.servlet; 
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; 
 
// Online population statistics listener implementation class  
public class OnlineListener implements ServletContextListener, 
  HttpSessionAttributeListener, HttpSessionListener { 
 private ServletContext application = null; 
 
 public void contextDestroyed(ServletContextEvent arg0) { 
  // TODO Auto-generated method stub 
 
 } 
  
 public void contextInitialized(ServletContextEvent arg0) { 
  // Initialize the 1 a application object  
  this.application = arg0.getServletContext(); 
  // Set up the 1 The list of properties used to save the user name in thought  
  this.application.setAttribute("online", new LinkedList<String>()); 
 
 } 
 // A method that is called back when a property is added to a session  
 public void attributeAdded(HttpSessionBindingEvent arg0) { 
  // Get a list of user names  
  List<String> online = (List<String>) this.application 
    .getAttribute("online"); 
  if ("username".equals(arg0.getName())) { 
   // Adds the current user name to the list  
   online.add((String) arg0.getValue()); 
  } 
  // Reset the added list to application Properties of the  
  this.application.setAttribute("online", online); 
 } 
 
 public void attributeRemoved(HttpSessionBindingEvent arg0) { 
  // TODO Auto-generated method stub 
 
 } 
 
 public void attributeReplaced(HttpSessionBindingEvent arg0) { 
  // TODO Auto-generated method stub 
 
 } 
 
 public void sessionCreated(HttpSessionEvent arg0) { 
  // TODO Auto-generated method stub 
 
 } 
 // Method to call back when a session is destroyed  
 public void sessionDestroyed(HttpSessionEvent arg0) { 
  // Get a list of user names  
  List<String> online = (List<String>) this.application 
    .getAttribute("online"); 
  // Gets the current user name  
  String username = (String) arg0.getSession().getAttribute("username"); 
  // Remove this user name from the list  
  online.remove(username); 
  // Reset the deleted list to application Properties of the  
  this.application.setAttribute("online", online); 
 } 
 
} 

(2) register the listener in web.xml

Once the listener is implemented, it needs to be registered in the web.xml file to work, just add the element in web.xml as follows


<!--  registered 1 A listener  -->
 <listener>
 <!--  Specifies the fully qualified name of the listener implementation class  -->
 <listener-class>
 com.web.servlet.OnlineListener
 </listener-class>
 </listener

Finally, we create several Servlet to test the functionality implemented by this listener.

Servlet class code for handling user login:


package com.web.servlet; 
 
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; 
 
// Handles user logins Servlet 
public class LoginServlet 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 appropriate content type  
   
  String username= request.getParameter("username");// Gets the user name in the request parameter  
   
  // to session Add attributes in , Will trigger HttpSessionAttributeListener In the attributeAdded methods  
  if(username != null && !username.equals("")) {  
   request.getSession().setAttribute("username",username);  
  } 
  // Get a list of online user names 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("<HTML>"); 
  out.println(" <HEAD><TITLE> List of users </TITLE></HEAD>"); 
  out.println(" <BODY>"); 
  out.println(" The 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)); 
  } 
   
  // Pay attention to :  Want to link URL Perform automatic rewrite processing  
  out.println("<hr/><a href="/" mce_href="/""" + response.encodeURL("logout") + "/"> The cancellation </a>"); 
  out.println(" </BODY>"); 
  out.println("</HTML>"); 
  out.flush(); 
  out.close(); 
 } 
} 

Handles the class code for the user to log on to Servlet


package com.web.servlet; 
 
import java.io.*; 
import java.util.List; 
import javax.servlet.ServletException; 
import javax.servlet.http.*; 
 
// Handles user logout sessions Servlet 
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"); 
   
  // Destroy the session , Will trigger SessionLinstener In the sessionDestroyed methods  
  request.getSession().invalidate(); 
   
  // Get a list of online user names 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("<HTML>"); 
  out.println(" <HEAD><TITLE> List of users </TITLE></HEAD>"); 
  out.println(" <BODY>"); 
  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="/" mce_href="/""index.html/"> The home page </a>"); 
  out.println(" </BODY>"); 
  out.println("</HTML>"); 
  out.flush(); 
  out.close(); 
 } 
} 

Then create an index.html file for users to log in. The code is as follows:


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 
<html> 
 <head> 
 <meta http-equiv="content-type" content="text/html; charset=UTF-8"> 
 <title>index.html</title> 
 </head> 
 
 <body> 
 <form action = "login" method = "post"> 
   User name: <input type ="text" name = "username"/> 
  <input type = "submit" value = " The login "/><br/><br/> 
  
 </form> 
 </body> 
</html> 

Deploy WEB to Tomcat container master and start. Open a browser to access it


Related articles: