Java using a listener to implement a statistical site online number of examples _java

Source: Internet
Author: User
Tags flush int size stub knowledge base

This article mainly introduces the Java use Listener to achieve a statistical site online number of examples, with a certain reference value, there is a need for friends to understand.

(1) Create a listener implementation class

To roughly count the number of people online on a website, first, you can listen by Servletcontextlistener, and when the Web application context starts, add a list to the ServletContext to prepare the username for the online user; The user name can be stored in the list of ServletContext when the user's login is successfully set to the session by Httpsessionattributelistener listening Finally, the user name is removed from the list of list in the application context when the user logs off the session through Httpsessionlistener listening.

So, write Onlinelistener class implement Servletcontextlistener, Httpsessionattributelistener, Httpsessionlistener interface, the specific code is as follows:

Package com.web.servlet; Import <a href= "Http://lib.csdn.net/base/javaee" class= ' Replace_word ' title= ' Java ee Knowledge Base ' target= ' _blank ' style= ' Color: #df3434; Font-weight:bold; ' >java</a>.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, httpsess 
 
  Ionlistener {private ServletContext application = null;  public void contextdestroyed (Servletcontextevent arg0) {//TODO auto-generated a stub} public void Contextinitialized (servletcontextevent arg0) {//initialization of a Application object this.application = Arg0.getservletcontext (); 
 
  Sets a list property that is used to save the user name This.application.setAttribute ("online", New Linkedlist<string> ()); The method that is invoked when adding properties to the session is public void attributeadded (Httpsessionbindingevent arg0) {//Get the list of user names List<string&gt ; 
    Online = (list<string>) this.application. getattribute ("online"); 
    if ("username". Equals (Arg0.getname ())) {//Add the current user name to the list Online.add ((String) arg0.getvalue ()); 
  ///Reset the added list to the Application property This.application.setAttribute ("Online", online); } public void attributeremoved (Httpsessionbindingevent arg0) {//TODO auto-generated method stub} PU Blic void attributereplaced (Httpsessionbindingevent arg0) {//TODO auto-generated method stub} public Voi D sessioncreated (httpsessionevent arg0) {//TODO auto-generated Method stub}////session will be callback when destroyed by public void s Essiondestroyed (httpsessionevent arg0) {//Get user Name list list<string> online = (list<string>) this.application getattribute ("online"); 
    Gets the current user name String username = (string) arg0.getsession (). getattribute ("username"); 
    Remove the user name from the list online.remove (username); 
  Reset the deleted list to the Application property This.application.setAttribute ("Online", online); 
 } 
 
}

(2) Registering the listener in the Web.xml

After the listener is implemented, you also need to register in the Web.xml file to work, just add elements like the following in Web.xml

<!--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 a few servlet to test the functionality of this listener implementation.

Servlet class code to process user logins:

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; Process user logon Servlet public class Loginservlet extends HttpServlet {public void doget (HttpServletRequest request, HttpS 
  Ervletresponse response) throws Servletexception, IOException {this.dopost (request, response); public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, Ioexce ption {request.setcharacterencoding ("utf-8");/Set appropriate content type String username= request.getparameter ("username") ;//Get user name in Request parameter//Add attribute to session, trigger attributeadded method in Httpsessionattributelistener if (username!= null &    
    &!username.equals ("")) {request.getsession (). setattribute ("username", username); } 
    //from the application context to get the list of online user names list<string> on-line = (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 ("Current user is:" + username); 
 
    Out.print (" 

Class code to process user logon servlet

Package com.web.servlet; 
Import java.io.*; 
Import java.util.List; 
Import javax.servlet.ServletException; 
 
Import javax.servlet.http.*; Servlet public class Logoutservlet extends HttpServlet {public void doget for processing user logoff sessions (HttpServletRequest request, Ht 
  Tpservletresponse response) throws Servletexception, IOException {this.dopost (request, response); public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, Ioexce 
     
    ption {request.setcharacterencoding ("utf-8");  
     
    Destroying the session triggers the Sessiondestroyed method Request.getsession () in the Sessionlinstener (). invalidate (); 
     
    Get online list of 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> user list </TITLE></HEAD>"); 
    Out.println ("<BODY>"); 
 
    Out.print (" 

Then create a index.html file for the user to log in with the following code:

<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" > 
 
 

Deploy the Web to the Tomcat container total and start. Open browser Access can

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.