This article mainly introduces an example of using listeners to java to count the number of people online on a website. It has certain reference value. Friends in need can learn about it.
(1) Create a listener implementation class
To roughly count the number of people online on a website, first, you can listen through the ServletContextListener. When the web application context is started, add a List in the ServletContext to prepare the username stored in the online; then, you can listen through the HttpSessionAttributeListener. When the user logs in successfully set the username to the Session, the username is stored in the List list in the ServletContext at the same time; finally, listen through the HttpSessionListener. When the user logs out of the session, the username is deleted from the List list in the application context.
Therefore, write the OnLineListener class to implement the 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 user 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 an application object this.application = arg0.getServletContext(); //Set a list attribute to save the username this.application.setAttribute("online", new LinkedList<String>()); } //Method that will callback when adding attributes to the session public void attributeAdded(HttpSessionBindingEvent arg0) { //Get the username list List<String> online = (List<String>) this.application .getAttribute("online"); if ("username".equals(arg0.getName())) { //Add the current username to the list online.add((String) arg0.getValue()); } //Reset the added list to the application attribute 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 that will callback when the session is destroyed public void sessionDestroyed(HttpSessionEvent arg0) { //Get the username list List<String> online = (List<String>) this.application .getAttribute("online"); //Get the current username String username = (String) arg0.getSession().getAttribute("username"); //Delete this username from the list online.remove(username); //Reset the deleted list into the application property this.application.setAttribute("online", online); } } (2) Register the listener in web.xml
After the listener is implemented, it also needs to register in the web.xml file to work. You only need to add elements in the web.xml as follows.
<!-- Register a listener --> <listener> <!-- Specify the fully qualified name of the listener implementation class --> <listener-class> com.web.servlet.OnlineListener </listener-class> </listener
Finally, we create several Servlets 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.HttpServletRequest; import javax.servlet.http.HttpServletResponse; //Servlet handling user login 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 corresponding content type String username= request.getParameter("username");//Get the user name in the request parameter//Adding 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"); response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); out.println("<HTML>"); out.println(" <HEAD><TITLE>User List</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)); } //Note: To automatically rewrite the link URL out.println("<hr/><a href="/" mce_href="/""" + response.encodeURL("logout") + "/">Logout</a>"); out.println(" </BODY>"); out.println("</HTML>"); out.flush(); out.close(); } } Class code for handling user login to Servlet
package com.web.servlet; import java.io.*; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.*; //Servlet that handles user logout session 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, the sessionDestroyed method in the SessionLinstener will be triggered 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("<HTML>"); out.println(" <HEAD><TITLE>User List</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/">Home</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"> Username: <input type ="text" name = "username"/> <input type = "submit" value = "Login"/><br/><br/> </form> </body> </html>
Deploy WEB to Tomcat container total and start. Open the browser to access
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.