How to capture the session event in the servlet

xiaoxiao2021-03-06  67

The meaning of capturing the session event: 1. Record the customer's customer login log (login, exit information, etc.) 2, statistics online number 3, etc. There are still many, huh, huh, you think it is 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: to achieve a listener: // SessionListener.javaimport java.io *; import java.util *; import javax.servlet.http *; // login monitor the entire process public class SessionListener implements HttpSessionBindingListener {public String... PrivateInfo = ""; // Generate the initialization parameter string 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 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.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 in Append mode File Foo.write (logstring.getbytes (), 0, logstring.Length ()); // Write log string foo.close (); break; // exit}} catch (filenotfoundexception e) {} catch (IOException E) ) {}} public void valueUnbound (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.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 the APPEND (logString.getBytes (), 0, logstring.length ()); // Write log string foo.close (); break; // exit}} catch FilenotFoundException E) {} catch (ooException e) {}}} Login log implementation: Let's take a look at some of our source code to use this listener in our login servlet: ... httpsession session = req.getsession; ... ... /// sessionListener sessionListener = new sessionListener ("IP:" Req.getRemoteAdddr ()); // Start a listener session.settribute ("listener", sessionListener for each session process; // Listener Implant 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. Login population in statistics: ServletContext session1 = getServletConfig () getServletContext (); // get ServletContext object instance if ((SessionListener) session1.getAttribute ( "listener1") == null) {SessionListener sessionListener1 = new SessionListener ( "count"). ; // Only one time, different from the record of the above log files set each session. 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.gettribute ("Listener1"))); // Remove this global object, and bind this object into a session, this object will cause the listener to call ValueBound, The counter adds one.

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

New Post(0)