How the session event is captured in the servlet

Source: Internet
Author: User
Tags log log
Capture the meaning of the session event:

1, record the site's customer login log (login, exit information, etc.)

2, Statistics online number

3, and so on there are a lot of, oh, I think it ... Anyway, it's very important.

Session represents the client's conversation process, and when the customer logs in, an object is passed in to the session to track the client's sessions. In the servlet, the object passing in the session is an object that implements the Httpsessionbindinglistener interface (for convenience, this object is called a listener), When it is passed in (that is, when the HttpSession object's SetAttribute method is invoked) and when it is removed (that is, when the RemoveAttribute method of the HttpSession object is invoked or session time Out time) The session object automatically invokes the Valuebound and Valueunbound methods of the listener (this is the method in the Httpsessionbindinglistener interface). So, log in is not difficult to achieve.

Another problem is how to count the number of online people, the problem is a little different from the implementation log log, the number of online statistics (and its information), is to count how many session instances exist now, we can add a counter (if you want to store more information, you can use an object to do the counter, Then given in the example, simple, with an integer variable as a counter, by the Valuebound method in the Counter add 1,valueunbound method in the counter minus 1, you can achieve the number of online statistics. Of course, this will take advantage of the global nature of the ServletContext. (Refer to the servlet specification for a description of ServletContext), create a new listener, and deposit its instance into ServletContext properties to ensure uniqueness of this listener instance, when the client logs on, First determine whether the ServletContext property is empty, if not NULL, the proof has been created, directly put this property into the session, the Counter plus 1, if empty, create a new listener, and into the ServletContext properties.

An example is provided:

   Implement a listener:

Sessionlistener.java import java.io.*;
                        Import java.util.*;
                        Import javax.servlet.http.*;
                        The entire process of listening for logins public class Sessionlistener implements Httpsessionbindinglistener {public string privateinfo= ' ";//Generate Listener's initialization parameter string private string logst Ring= ""; Log record string private int count=0;
                        Number of logged-in counters public sessionlistener (String info) {this.privateinfo=info;
                        public int GetCount () {return count;
                        } public void Valuebound (Httpsessionbindingevent event) {
                        count++; if (Privateinfo.equals ("Count")) {return;
                        } try{Calendar calendar=new GregorianCalendar ();
                        System.out.println ("LOGIN:" +privateinfo+ "Time:" +calendar.gettime ());
                        logstring= "/nlogin:" +privateinfo+ "Time:" +calendar.gettime () + "n";
                        for (int i=1;i<1000;i++) {file File=new file ("Yeeyoo.log" +i); if (!) ( File.exists ()) file.createnewfile (); 
                        If the file does not exist, create this file if (File.length () >1048576)//If the file is greater than 1M, recreate a file continue;
                        FileOutputStream foo=new FileOutputStream ("Yeeyoo.log" +i,true); Open the Create file in Append Foo.write (Logstring.getbytes (), 0,logstring.length ());
                        Writes the log string Foo.close (); break;//exit}}catch (filenotfoundexceptIon e) {} catch (IOException e) {}} public void Valu
                        Eunbound (Httpsessionbindingevent event) {count--;
                        if (Privateinfo.equals ("Count")) {return;
                        } try{Calendar calendar=new GregorianCalendar ();
                        System.out.println ("LOGOUT:" +privateinfo+ "Time:" +calendar.gettime ());
                        logstring= "/nlogout:" +privateinfo+ "Time:" +calendar.gettime () + "n";
                        for (int i=1;i<1000;i++) {file File=new file ("Yeeyoo.log" +i); if (!) ( File.exists ()) file.createnewfile (); 
                        If the file does not exist, create this file if (File.length () >1048576)//If the file is greater than 1M, recreate a file continue; FileoUtputstream foo=new FileOutputStream ("Yeeyoo.log" +i,true); Open the Create file in Append Foo.write (Logstring.getbytes (), 0,logstring.length ());
                        Writes the log string Foo.close (); break;//exit}}catch (FileNotFoundException e) {} cat CH (IOException e) {}}}


implementation of login log:

Let's take a look at some of the source code in our login servlet that uses this listener:

                        ..... HttpSession session = Req.getsession (true);
                        .....
                        Sessionlistener sessionlistener=
                        New Sessionlistener ("IP:" +req.getremoteaddr ());
                        Start a listener
                        session.setattribute ("Listener", Sessionlistener) for each session process;
                        The listener is implanted into the httpsession, which fires the listener to invoke the Valuebound method,
                        //thereby logging the log file.
                        //////////////////////////////////////////////////////////////////


When the system exits login, simply call Session.removeattribute ("listener");

The Valueunbound method of the listener can be invoked automatically. Alternatively, this method is called when session time is out.

number of logged in statistics:

 servletcontext session1=getservletconfig (). Getservletcontext ();
                        Gets the ServletContext object instance if ((Sessionlistener) Session1.getattribute ("Listener1") ==null)
                        {Sessionlistener sessionlistener1=new Sessionlistener ("Count");
                        Set only once, unlike records on the log file above, each session is set.
                        That is, when the first client connects to the server, it starts a global variable, and//thereafter all customers will use the same context.
                        Session1.setattribute ("Listener1", sessionListener1);
                        Setting the Listener object to a ServletContext property, with global scope validity,//That is, all customers can get an instance of it.
                        } session.setattribute ("Listener1", (Sessionlistener) Session1.
                        GetAttribute ("Listener1")); Remove this global object and bind this object to a session,//This will cause the listener to invoke Valuebound, counter plus one. 


The following code can be used at any time in this program to get the current number of logins:

((Sessionlistener) Session.getattribute ("Listener1")). GetCount ()


GetCount () is a method of the listener that gets the value of the current counter, which is the number of logins.

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.