Java is a method based on servlet listener to realize online population monitoring function

  • 2020-12-13 18:58:21
  • OfStack

An example of Java based on servlet listener is presented in this paper. To share for your reference, the details are as follows:

1. Analysis:

To count the online number of a website, you can listen through ServletContextListener. When the Web application context starts, add 1 List to ServletContext. It is used to prepare the online user name and then listens through HttpSessionAttributeListener. When the user logs in successfully, the user name is set to Session. At the same time, the user name method is added to ServletContext's List, and finally listens through HttpSessionListener. When the user logs out of the session, the user name is deleted from the List list in the application context scope.

2. Matters needing attention

During the test, you need to launch different browsers to log in different users. Only by clicking the logout button can you reduce the number of online users, while closing the browser cannot reduce the number of 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;
  // A method that is called back when the context is initially applied 
  @Override
  public void contextInitialized(ServletContextEvent e) {
    // Initialize the 1 a application object 
    application = e.getServletContext();
    // Set up the 1 A list property that holds the online user name 
    this.application.setAttribute("online", new LinkedList<String>());
  }
  // Callback method when adding a property to the session 
  @Override
  public void attributeAdded(HttpSessionBindingEvent e) {
    // Gets a list of user names 
    List<String> onlines = (List<String>) this.application.getAttribute("online");
    if("username".equals(e.getName())){
      onlines.add((String) e.getValue());
    }
    // Resets the column for the added list application Properties of the .
    this.application.setAttribute("online", onlines);
  }
  // Methods that call back when a session is destroyed 
  @Override
  public void sessionDestroyed(HttpSessionEvent e) {
    // Gets a list of user names 
    List<String> onlines = (List<String>) this.application.getAttribute("online");
    // Gets the current user name 
    String username = (String) e.getSession().getAttribute("username");
    // Delete this user from the list 
    onlines.remove(username);
    // To reset the deleted list to application Properties of the .
    this.application.setAttribute("online", onlines);
  }
  public void sessionCreated(HttpSessionEvent e) {}
  public void attributeRemoved(HttpSessionBindingEvent e) {}
  public void attributeReplaced(HttpSessionBindingEvent e) {}
  public void contextDestroyed(ServletContextEvent 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.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");  // Gets the user name in the request parameter 
        // to session Add attributes to , Will trigger HttpSessionAttributeListener In the attributeAdded methods 
        if(username != null && !username.equals("")) {
          request.getSession().setAttribute("username",username);
        }
        // Gets a list of online user names 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> List of users </title>");
        out.println(" ");
        out.println(" The current user is: " + username);
        out.print("  <hr><h3> List of online users </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 Do automatic rewrite processing 
        out.println("<hr/><a href=\"" + response.encodeURL("logoutListener") + "\"> The cancellation </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 , Will trigger SessionLinstener In the sessionDestroyed methods 
    request.getSession().invalidate();
    // Gets 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("");
    out.println(" <title> List of users </title>");
    out.println(" ");
    out.print("  <h3> List of online users </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\''> The home page </a>");
    out.println(" ");
    out.println("");
    out.flush();
    out.close();
  }
}

(2) ES40en. 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/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">
     User name: <input type="text" name="username">
  <input type="submit" value=" The login "><br><br>
  </form>
 </body>
</html>

For more information about java algorithm, please refer to Java Network programming Skills summary, Java Data Structure and Algorithm Tutorial, Java Operation of DOM Node Skills Summary, Java File and directory Operation Skills Summary and Java Cache operation Skills Summary.

I hope this article has been helpful to you in java programming.


Related articles: