How to capture the session event in the servlet?

xiaoxiao2021-03-06  55

The meaning of capturing session events:

1. Record the customer login log (login, exit information, etc.)

2, statistics online number

3, etc. There are still a lot, huh, I think ... I am very important.

Session represents a customer's session process, when you log in, you will pass an object to the Session to track the customer's session. In Servlet, the object that is incompanded if it is an object that implements the HttpSessionBindingListener interface (convenient, this object is called a listener), then when it is incorporated (ie, when calling the setattribute method of the httpsession object) and removed The session object will automatically call the listener valueBound and ValueunBound method (this is the method of the HttpSessionBindingListener interface).

It can be seen that the login log is not difficult to achieve.

Another problem is how to count online, this problem is a bit different from the login log, statistics online number (and its information), is the statistics now how many session instances exist, we can add a counter (if you want to store more Information, you can use an object to do a counter. In the example, simply play, use an integer variable as a counter, by adding 1, the counter is added to the counter in the valueunbound method, you can implement online Statistics of the number. Of course, this should be used to use the global feature of servletContext. (Refer to the Servlet specification for the narrative of ServletContext), create a new listener and store it into the properties of servletContext to ensure that this listener instance is unique, when the customer logs in, first determined whether the attribute of servletContext is Empty, if not empty, demonstrate that you have created, remove this property into the session, the counter plus 1; if you are empty, create a new listener and store the properties of ServletContext.

for example:

Implement a listener:

// sessionListener.java

Import java.io. *;

Import java.util. *;

Import javax.servlet.http. *;

// Monitor the entire process of login

Public Class SessionListener Implements HttpSessionBindingListener

{

Public String PrivateInfo = ""; // Generate the initialization parameter string of the listener

Private string logstring = ""; // logging string

Private int count = 0; // login number counter

Public sessionListener (String info) {

THIS.PRIVATEINFO = INFO;

}

Public int getCount () {

Return count;

}

Public void valuebound (httpsessionBindingEvent evenet)

{

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.exiss ())))

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 creation file in Append mode

foo.write (logstring.getbytes (), 0, logstring.length ()); // Write log string

FOO.CLOSE ();

Break; // exit

}

} catch (filenotfoundexception e) {}

Catch (IOException E) {}

}

Public void valueunbound (httpsessionBindingEvent evenet)

{

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.exiss ())))

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 creation file in Append mode

foo.write (logstring.getbytes (), 0, logstring.length ()); // Write log string

FOO.CLOSE ();

Break; // exit

}

} catch (filenotfoundexception e) {}

Catch (IOException E) {}

}

}

Realization of login logs:

Let's take a look at some of our source code to use this listener in our login servlet:

......

HttpSession session = req.getations (TRUE); ......

///

SessionListener sessionListener = New sessionListener ("IP:" Req.getRemoteAddddddr ()); // Start a listener for each session process

Session.setttribute ("Listener", sessionListener; // Implants httpsession, which will activate the listener to call the valueBound method to log files.

///

When the system exits login, simply call session.removeattribute ("Listener"); you can automatically call the listener's valueunBound method. Or, this method will also be called when session time out is.

Statistics of the number of logins:

ServletContext session1 = getServletConfig (). GetServletContext (); // get a servletContext object instance

IF (sessionListener) session1.getattribute ("Listener1") == NULL)

{

SessionListener sessionListener1 = new sessionListener ("count"); // only set once, different from the log file records all sessions. That is, a global variable is initiated when the first client is connected to the server, and thereafter all customers will use the same context.

Session1.setttribute ("Listener1", sessionListener1); // Set the monitor object to servletContext properties, with global validity, that is, all customers can get its instance.

}

Session.setttribute ("Listener1", ("Listener1", Session1.GetaTRibute ("Listener1"))); // Remove this global object, and bind this object into a session, this will prompt the listener to call ValueBound, counter plus one.

You can use the following code to get the current number of logins at any time in the program:

(SessionListener) Session.getaTribute ("Listener1")). Getcount ()

getCount () is a method of the listener, that is, the value of the current counter is also the number of logins.

Welcome to reprint in the case of retaining http://www.javajia.com!

转载请注明原文地址:https://www.9cbs.com/read-118011.html

New Post(0)